bee-tree/dist/demo.js

41832 lines
1.4 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _beeLayout = __webpack_require__(3);
var _beePanel = __webpack_require__(9);
var _beeDrawer = __webpack_require__(84);
var _beeDrawer2 = _interopRequireDefault(_beeDrawer);
var _beeClipboard = __webpack_require__(98);
var _beeClipboard2 = _interopRequireDefault(_beeClipboard);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var Demo1 = __webpack_require__(304);var Demo2 = __webpack_require__(305);var Demo3 = __webpack_require__(306);var Demo4 = __webpack_require__(307);var Demo5 = __webpack_require__(308);var Demo6 = __webpack_require__(309);var Demo7 = __webpack_require__(310);var Demo8 = __webpack_require__(311);var Demo9 = __webpack_require__(312);var Demo10 = __webpack_require__(313);var Demo11 = __webpack_require__(314);var Demo12 = __webpack_require__(315);var Demo13 = __webpack_require__(316);var Demo14 = __webpack_require__(317);var DemoArray = [{ "example": _react2['default'].createElement(Demo1, null), "title": " Tree基本使用示例", "code": "/**\r\n *\r\n * @title Tree基本使用示例\r\n * @description 示例涵盖 checkbox如何选择disable状态和部分选择状态。checkStrictly为true时子节点与父节点的选择情况都不会影响到对方\r\n *\r\n */\r\n\r\n\r\nimport React, {\r\n\tComponent\r\n} from 'react';\r\n\r\n\nconst TreeNode = Tree.TreeNode;\r\n\r\nconst defaultProps = {\r\n\tkeys: ['0-0-0', '0-0-1']\r\n}\r\nclass Demo1 extends Component {\r\n\tconstructor(props) {\r\n\t\tsuper(props);\r\n\t\tconst keys = this.props.keys;\r\n\t\tthis.state = {\r\n\t\t\tdefaultExpandedKeys: keys,\r\n\t\t\tdefaultSelectedKeys: keys,\r\n\t\t\tdefaultCheckedKeys:keys,\r\n\t\t\tcheckedKeys: {checked:keys},\r\n\t\t};\r\n\t}\r\n\tonSelect(info) {\r\n\t\tconsole.log('selected', info);\r\n\t}\r\n\tonCheck = (checkedKeys,newst) => {\r\n\t\t//用户可以自定义当前选中和半选中的节点。\r\n\t\tconsole.log('onCheck', checkedKeys);\r\n\t\tconst cks = {\r\n\t\t\tchecked: checkedKeys.checked || checkedKeys,\r\n\t\t\thalfChecked:checkedKeys.halfChecked\r\n\t\t};\r\n\t\tthis.setState({checkedKeys:cks});\r\n\t}\r\n\r\n\tonDoubleClick=(key,treeNode)=>{\r\n\t\tconsole.log('---onDblClick---',key,'--treeNode--',treeNode);\r\n\t}\r\n\trender() {\r\n\t\r\n\t\treturn (\r\n\t\t\t<Tree \r\n className=\"myCls\" \r\n showLine \r\n checkable\r\n defaultExpandedKeys={this.state.defaultExpandedKeys}\r\n defaultSelectedKeys={this.state.defaultSelectedKeys}\r\n defaultCheckedKeys = {this.state.defaultCheckedKeys}\r\n checkStrictly\r\n showIcon\r\n cancelUnSelect={true}\r\n onSelect={this.onSelect} \r\n onCheck={this.onCheck}\r\n onDoubleClick={this.onDoubleClick}\r\n\t >\r\n\t <TreeNode title=\"parent 1\" key=\"0-0\" icon={<Icon type=\"uf-treefolder\" />}>\r\n\t <TreeNode title=\"parent 1-0\" key=\"0-0-0\" disabled icon={<Icon type=\"uf-treefolder\" />}>\r\n\t <TreeNode title=\"leaf\" key=\"0-0-0-0\" disableCheckbox icon={<Icon type=\"uf-list-s-o\" />}/>\r\n\t <TreeNode title=\"leaf\" key=\"0-0-0-1\" icon={<Icon type=\"uf-list-s-o\" />}/>\r\n\t </TreeNode>\r\n\t <TreeNode title=\"parent 1-1\" key=\"0-0-1\" icon={<Icon type=\"uf-treefolder\" />}>\r\n\t <TreeNode title={<span>sss</span>} key=\"0-0-1-0\" icon={<Icon type=\"uf-list-s-o\" />}/>\r\n\t </TreeNode>\r\n\t </TreeNode>\r\n\t </Tree>\r\n\t\t);\r\n\t}\r\n}\r\n\r\nDemo1.defaultProps = defaultProps;\r\n\r\n\r\nexport default Demo1;", "desc": " 示例涵盖 checkbox如何选择disable状态和部分选择状态。checkStrictly为true时子节点与父节点的选择情况都不会影响到对方" }, { "example": _react2['default'].createElement(Demo2, null), "title": " Tree数据可控示例", "code": "/**\r\n*\r\n* @title Tree数据可控示例\r\n* @description\r\n* \b\r\n*/\r\n\r\nimport React, { Component } from 'react';\nimport { Tree } from 'tinper-bee';\r\n\r\n\r\nconst x = 6;\r\nconst y = 5;\r\nconst z = 2;\r\nconst gData = [];\r\n\r\nconst generateData = (_level, _preKey, _tns) => {\r\n const preKey = _preKey || '0';\r\n const tns = _tns || gData;\r\n\r\n const children = [];\r\n for (let i = 0; i < x; i++) {\r\n const key = `${preKey}-${i}`;\r\n tns.push({ title: key, key });\r\n if (i < y) {\r\n children.push(key);\r\n }\r\n }\r\n if (_level < 0) {\r\n return tns;\r\n }\r\n const level = _level - 1;\r\n children.forEach((key, index) => {\r\n tns[index].children = [];\r\n return generateData(level, key, tns[index].children);\r\n });\r\n};\r\ngenerateData(z);\r\n\r\nconst TreeNode = Tree.TreeNode;\r\n\r\n\r\nclass Demo2 extends Component{\r\n constructor(props) {\r\n \tsuper(props);\r\n this.state = {\r\n expandedKeys: [],\r\n autoExpandParent: true,\r\n checkedKeys: ['0-0-0'],\r\n selectedKeys: [],\r\n };\r\n this.onExpand = this.onExpand.bind(this);\r\n this.onCheck = this.onCheck.bind(this);\r\n this.onSelect = this.onSelect.bind(this);\r\n }\r\n onExpand(expandedKeys) {\r\n console.log('onExpand', arguments);\r\n // if not set autoExpandParent to false, if children expanded, parent can not collapse.\r\n // or, you can remove all expanded children keys.\r\n this.setState({\r\n expandedKeys,\r\n autoExpandParent: false,\r\n });\r\n }\r\n onCheck(checkedKeys) {\r\n this.setState({\r\n checkedKeys,\r\n selectedKeys: ['0-3', '0-4'],\r\n });\r\n }\r\n onSelect(selectedKeys, info) {\r\n console.log('onSelect', info);\r\n this.setState({ selectedKeys });\r\n }\r\n // keydown的钩子事件\r\n onKeyDown = (e,treeNode)=>{\r\n console.log('***',e);\r\n return false;\r\n }\r\n render() {\r\n const loop = data => data.map((item) => {\r\n if (item.children) {\r\n return (\r\n <TreeNode key={item.key} title={item.key} disableCheckbox={item.key === '0-0-0'} ext={{'as':'sdfa'}}>\r\n {loop(item.children)}\r\n </TreeNode>\r\n );\r\n }\r\n return <TreeNode key={item.key} title={item.key} isLeaf={true}/>;\r\n });\r\n return (\r\n <Tree\r\n checkable\r\n focusable\r\n className=\"demo2 myCls\"\r\n onExpand={this.onExpand} expandedKeys={this.state.expandedKeys}\r\n autoExpandParent={this.state.autoExpandParent}\r\n onCheck={this.onCheck} \r\n onSelect={this.onSelect} \r\n keyFun={this.onKeyDown}\r\n >\r\n {loop(gData)}\r\n </Tree>\r\n );\r\n }\r\n};\r\n\r\n\r\nexport default Demo2;", "desc": "", "scss_code": "// .demo2.u-tree {\r\n// li a.u-tree-node-content-wrapper:hover::before {\r\n// background: rgb(235, 236, 240);\r\n// }\r\n// li a.u-tree-node-content-wrapper.u-tree-node-selected {\r\n// color: rgb(245, 60, 50);\r\n// .u-tree-title{\r\n// color: rgb(245, 60, 50);\r\n// }\r\n// background: transparent;\r\n// &::before {\r\n// background: rgb(235, 236, 240);\r\n// }\r\n// }\r\n\r\n// li a.u-tree-node-content-wrapper::before {\r\n// position: absolute;\r\n// right: 0;\r\n// left: 0;\r\n// height: 20px;\r\n// -webkit-transition: all 0.3s;\r\n// transition: all 0.3s;\r\n// content: \"\";\r\n// }\r\n\r\n// li span {\r\n// position: relative;\r\n// z-index: 1;\r\n// }\r\n// }\r\n" }, { "example": _react2['default'].createElement(Demo3, null), "title": " Tree 拖拽使用示例", "code": "/**\r\n*\r\n* @title Tree 拖拽使用示例\r\n* @description 拖动结点插入到另一个结点后面或者其他的父节点里面。\r\n*\r\n*/\r\n\r\n\r\n\r\nimport React, { Component } from 'react';\nimport { Tree } from 'tinper-bee';\r\n\r\n\r\nconst x = 3;\r\nconst y = 2;\r\nconst z = 1;\r\nconst gData = [];\r\n\r\nconst generateData = (_level, _preKey, _tns) => {\r\n const preKey = _preKey || '0';\r\n const tns = _tns || gData;\r\n\r\n const children = [];\r\n for (let i = 0; i < x; i++) {\r\n const key = `${preKey}-${i}`;\r\n tns.push({ title: key, key });\r\n if (i < y) {\r\n children.push(key);\r\n }\r\n }\r\n if (_level < 0) {\r\n return tns;\r\n }\r\n const level = _level - 1;\r\n children.forEach((key, index) => {\r\n tns[index].children = [];\r\n return generateData(level, key, tns[index].children);\r\n });\r\n};\r\ngenerateData(z);\r\n\r\nconst TreeNode = Tree.TreeNode;\r\n\r\nclass Demo3 extends Component{\r\n constructor(props) {\r\n super(props);\r\n this.state = {\r\n gData,\r\n expandedKeys: ['0-0', '0-0-0', '0-0-0-0'],\r\n };\r\n this.onDragEnter = this.onDragEnter.bind(this);\r\n this.onDrop = this.onDrop.bind(this);\r\n }\r\n onDragEnter(info) {\r\n console.log(info);\r\n // expandedKeys 需要受控时设置\r\n // this.setState({\r\n // expandedKeys: info.expandedKeys,\r\n // });\r\n }\r\n onDrop(info) {\r\n console.log(info);\r\n const dropKey = info.node.props.eventKey;\r\n const dragKey = info.dragNode.props.eventKey;\r\n // const dragNodesKeys = info.dragNodesKeys;\r\n const loop = (data, key, callback) => {\r\n data.forEach((item, index, arr) => {\r\n if (item.key === key) {\r\n return callback(item, index, arr);\r\n }\r\n if (item.children) {\r\n return loop(item.children, key, callback);\r\n }\r\n });\r\n };\r\n const data = [...this.state.gData];\r\n let dragObj;\r\n loop(data, dragKey, (item, index, arr) => {\r\n arr.splice(index, 1);\r\n dragObj = item;\r\n });\r\n if (info.dropToGap) {\r\n let ar;\r\n let i;\r\n loop(data, dropKey, (item, index, arr) => {\r\n ar = arr;\r\n i = index;\r\n });\r\n ar.splice(i, 0, dragObj);\r\n } else {\r\n loop(data, dropKey, (item) => {\r\n item.children = item.children || [];\r\n // where to insert 示例添加到尾部,可以是随意位置\r\n item.children.push(dragObj);\r\n });\r\n }\r\n this.setState({\r\n gData: data,\r\n });\r\n }\r\n render() {\r\n const loop = data => data.map((item) => {\r\n if (item.children && item.children.length) {\r\n return <TreeNode key={item.key} title={item.key}>{loop(item.children)}</TreeNode>;\r\n }\r\n return <TreeNode key={item.key} title={item.key} />;\r\n });\r\n return (\r\n <Tree\r\n className=\"myCls\"\r\n defaultExpandedKeys={this.state.expandedKeys}\r\n draggable\r\n onDragEnter={this.onDragEnter}\r\n onDrop={this.onDrop}\r\n >\r\n {loop(this.state.gData)}\r\n </Tree>\r\n );\r\n }\r\n};\r\n\r\nexport default Demo3;", "desc": " 拖动结点插入到另一个结点后面或者其他的父节点里面。" }, { "example": _react2['default'].createElement(Demo4, null), "title": " Tree可搜索示例", "code": "/**\r\n *\r\n * @title Tree可搜索示例\r\n * @description\r\n *\r\n */\r\n\r\n\r\nimport React, {\r\n Component\r\n} from 'react';\r\n\n\r\n\r\nconst x = 3;\r\nconst y = 2;\r\nconst z = 1;\r\nconst gData = [];\r\n\r\nconst generateData = (_level, _preKey, _tns) => {\r\n const preKey = _preKey || '0';\r\n const tns = _tns || gData;\r\n\r\n const children = [];\r\n for (let i = 0; i < x; i++) {\r\n const key = `${preKey}-${i}`;\r\n tns.push({\r\n title: key,\r\n key\r\n });\r\n if (i < y) {\r\n children.push(key);\r\n }\r\n }\r\n if (_level < 0) {\r\n return tns;\r\n }\r\n const level = _level - 1;\r\n children.forEach((key, index) => {\r\n tns[index].children = [];\r\n return generateData(level, key, tns[index].children);\r\n });\r\n};\r\ngenerateData(z);\r\n\r\nconst TreeNode = Tree.TreeNode;\r\n\r\nconst dataList = [];\r\nconst generateList = (data) => {\r\n for (let i = 0; i < data.length; i++) {\r\n const node = data[i];\r\n const key = node.key;\r\n dataList.push({\r\n key,\r\n title: key\r\n });\r\n if (node.children) {\r\n generateList(node.children, node.key);\r\n }\r\n }\r\n};\r\ngenerateList(gData);\r\n\r\nconst getParentKey = (key, tree) => {\r\n let parentKey;\r\n for (let i = 0; i < tree.length; i++) {\r\n const node = tree[i];\r\n if (node.children) {\r\n if (node.children.some(item => item.key === key)) {\r\n parentKey = node.key;\r\n } else if (getParentKey(key, node.children)) {\r\n parentKey = getParentKey(key, node.children);\r\n }\r\n }\r\n }\r\n return parentKey;\r\n};\r\n\r\n\r\nclass Demo4 extends Component {\r\n constructor(props) {\r\n super(props);\r\n this.state = {\r\n expandedKeys: [],\r\n searchValue: '',\r\n autoExpandParent: true,\r\n }\r\n }\r\n onExpand = (expandedKeys) => {\r\n this.setState({\r\n expandedKeys,\r\n autoExpandParent: false,\r\n });\r\n }\r\n onChange = (value) => {\r\n\r\n const expandedKeys = [];\r\n dataList.forEach((item) => {\r\n if (item.key.indexOf(value) > -1) {\r\n expandedKeys.push(getParentKey(item.key, gData));\r\n }\r\n });\r\n const uniqueExpandedKeys = [];\r\n expandedKeys.forEach((item) => {\r\n if (item && uniqueExpandedKeys.indexOf(item) === -1) {\r\n uniqueExpandedKeys.push(item);\r\n }\r\n });\r\n this.setState({\r\n expandedKeys: uniqueExpandedKeys,\r\n searchValue: value,\r\n autoExpandParent: true,\r\n });\r\n }\r\n render() {\r\n const {\r\n searchValue,\r\n expandedKeys,\r\n autoExpandParent\r\n } = this.state;\r\n const loop = data => data.map((item) => {\r\n const index = item.key.search(searchValue);\r\n const beforeStr = item.key.substr(0, index);\r\n const afterStr = item.key.substr(index + searchValue.length);\r\n const title = index > -1 ? (\r\n <span>\r\n {beforeStr}\r\n <span className=\"u-tree-searchable-filter\">{searchValue}</span>\r\n {afterStr}\r\n </span>\r\n ) : <span>{item.key}</span>;\r\n if (item.children) {\r\n return (\r\n <TreeNode key={item.key} title={title}>\r\n {loop(item.children)}\r\n </TreeNode>\r\n );\r\n }\r\n return <TreeNode key={item.key} title={title} />;\r\n });\r\n return (\r\n <div>\r\n <FormControl\r\n style={{ width: 200 }}\r\n placeholder=\"Search\"\r\n onChange={this.onChange}\r\n />\r\n <Tree\r\n className=\"myCls\"\r\n onExpand={this.onExpand}\r\n expandedKeys={expandedKeys}\r\n autoExpandParent={autoExpandParent}\r\n >\r\n {loop(gData)}\r\n </Tree>\r\n </div>\r\n );\r\n }\r\n}\r\n\r\nexport default Demo4;", "desc": "", "scss_code": ".u-tree-searchable-filter {\r\n color: #f50;\r\n transition: all .3s ease;\r\n}" }, { "example": _react2['default'].createElement(Demo5, null), "title": " Tree异步数据加载", "code": "/**\r\n *\r\n * @title Tree异步数据加载\r\n * @description 当点击展开,异步获取子节点数据\r\n *\r\n */\r\n\r\n\r\nimport React, {\r\n Component\r\n} from 'react';\r\n\r\n\r\nconst x = 3;\r\nconst y = 2;\r\nconst z = 1;\r\nconst gData = [];\r\n\r\nconst generateData = (_level, _preKey, _tns) => {\r\n const preKey = _preKey || '0';\r\n const tns = _tns || gData;\r\n\r\n const children = [];\r\n for (let i = 0; i < x; i++) {\r\n const key = `${preKey}-${i}`;\r\n tns.push({\r\n title: key,\r\n key\r\n });\r\n if (i < y) {\r\n children.push(key);\r\n }\r\n }\r\n if (_level < 0) {\r\n return tns;\r\n }\r\n const level = _level - 1;\r\n children.forEach((key, index) => {\r\n tns[index].children = [];\r\n return generateData(level, key, tns[index].children);\r\n });\r\n};\r\ngenerateData(z);\r\n\r\nconst TreeNode = Tree.TreeNode;\r\n\r\nfunction generateTreeNodes(treeNode) {\r\n const arr = [];\r\n const key = treeNode.props.eventKey;\r\n for (let i = 0; i < 3; i++) {\r\n arr.push({\r\n name: `leaf ${key}-${i}`,\r\n key: `${key}-${i}`\r\n });\r\n }\r\n return arr;\r\n}\r\n\r\nfunction setLeaf(treeData, curKey, level) {\r\n const loopLeaf = (data, lev) => {\r\n const l = lev - 1;\r\n data.forEach((item) => {\r\n if ((item.key.length > curKey.length) ? item.key.indexOf(curKey) !== 0 :\r\n curKey.indexOf(item.key) !== 0) {\r\n return;\r\n }\r\n if (item.children) {\r\n loopLeaf(item.children, l);\r\n } else if (l < 1) {\r\n item.isLeaf = true;\r\n }\r\n });\r\n };\r\n loopLeaf(treeData, level + 1);\r\n}\r\n\r\nfunction getNewTreeData(treeData, curKey, child, level) {\r\n const loop = (data) => {\r\n if (level < 1 || curKey.length - 3 > level * 2) return;\r\n data.forEach((item) => {\r\n if (curKey.indexOf(item.key) === 0) {\r\n if (item.children) {\r\n loop(item.children);\r\n } else {\r\n item.children = child;\r\n }\r\n }\r\n });\r\n };\r\n loop(treeData);\r\n setLeaf(treeData, curKey, level);\r\n}\r\n\r\nclass Demo5 extends Component {\r\n constructor(props) {\r\n super(props);\r\n this.state = {\r\n treeData: [],\r\n };\r\n this.onSelect = this.onSelect.bind(this);\r\n this.onLoadData = this.onLoadData.bind(this);\r\n }\r\n componentDidMount() {\r\n setTimeout(() => {\r\n this.setState({\r\n treeData: [{\r\n name: 'pNode 01',\r\n key: '0-0'\r\n }, {\r\n name: 'pNode 02',\r\n key: '0-1'\r\n }, {\r\n name: 'pNode 03',\r\n key: '0-2',\r\n isLeaf: true\r\n }, ],\r\n });\r\n }, 100);\r\n }\r\n onSelect(info) {\r\n console.log('selected', info);\r\n }\r\n onLoadData(treeNode) {\r\n return new Promise((resolve) => {\r\n setTimeout(() => {\r\n const treeData = [...this.state.treeData];\r\n getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 2);\r\n this.setState({\r\n treeData\r\n });\r\n resolve();\r\n }, 1000);\r\n });\r\n }\r\n render() {\r\n const loop = data => data.map((item) => {\r\n if (item.children) {\r\n return <TreeNode title={item.name} key={item.key}>{loop(item.children)}</TreeNode>;\r\n }\r\n return <TreeNode title={item.name} key={item.key} isLeaf={item.isLeaf} disabled={item.key === '0-0-0'} />;\r\n });\r\n const treeNodes = loop(this.state.treeData);\r\n return (\r\n <Tree className=\"myCls\" onSelect={this.onSelect} loadData={this.onLoadData} >\r\n {treeNodes}\r\n </Tree>\r\n );\r\n }\r\n};\r\n\r\nexport default Demo5", "desc": " 当点击展开,异步获取子节点数据" }, { "example": _react2['default'].createElement(Demo6, null), "title": " Tree基本使用示例自定义图标", "code": "/**\r\n *\r\n * @title Tree基本使用示例自定义图标\r\n * @description 添加openIcon、closeIcon属性\r\n *\r\n */\r\n\r\n\r\nimport React, {\r\n\tComponent\r\n} from 'react';\r\n\r\n\nconst TreeNode = Tree.TreeNode;\r\n\r\nconst defaultProps = {\r\n\tkeys: ['0-0-0', '0-0-1']\r\n}\r\nclass Demo1 extends Component {\r\n\tconstructor(props) {\r\n\t\tsuper(props);\r\n\t\tconst keys = this.props.keys;\r\n\t\tthis.state = {\r\n\t\t\tdefaultExpandedKeys: keys,\r\n\t\t\tdefaultSelectedKeys: keys,\r\n\t\t\tdefaultCheckedKeys: keys,\r\n\t\t};\r\n\t}\r\n\tonSelect(info) {\r\n\t\tconsole.log('selected', info);\r\n\t}\r\n\tonCheck(info) {\r\n\t\tconsole.log('onCheck', info);\r\n\t}\r\n\trender() {\r\n\t\treturn (\r\n\r\n\t\t\t<Tree className=\"myCls\" checkable openIcon={<Icon type=\"uf-minus\" />} closeIcon={<Icon type=\"uf-plus\" />}\r\n\t defaultExpandedKeys={this.state.defaultExpandedKeys}\r\n\t defaultSelectedKeys={this.state.defaultSelectedKeys}\r\n\t defaultCheckedKeys={this.state.defaultCheckedKeys}\r\n\t onSelect={this.onSelect} onCheck={this.onCheck}\r\n\t >\r\n\t <TreeNode title=\"parent 1\" key=\"0-0\">\r\n\t <TreeNode title=\"parent 1-0\" key=\"0-0-0\" disabled>\r\n\t <TreeNode title=\"leaf\" key=\"0-0-0-0\" disableCheckbox />\r\n\t <TreeNode title=\"leaf\" key=\"0-0-0-1\" />\r\n\t </TreeNode>\r\n\t <TreeNode title=\"parent 1-1\" key=\"0-0-1\">\r\n\t <TreeNode title={<span>sss</span>} key=\"0-0-1-0\" />\r\n\t </TreeNode>\r\n\t </TreeNode>\r\n\t </Tree>\r\n\t\t);\r\n\t}\r\n}\r\n\r\nDemo1.defaultProps = defaultProps;\r\n\r\n\r\nexport default Demo1;", "desc": " 添加openIcon、closeIcon属性" }, { "example": _react2['default'].createElement(Demo7, null), "title": " Tree增加节点", "code": "/**\r\n *\r\n * @title Tree增加节点\r\n * @description 增加节点和拖拽组合使用示例\r\n *\r\n */\r\n\r\n\r\nimport React, {\r\n Component\r\n} from 'react';\r\n\r\n\n\r\nconst TreeNode = Tree.TreeNode;\r\n\r\n\r\nclass Demo7 extends Component {\r\n constructor(props) {\r\n super(props);\r\n this.state = {\r\n treeData: [],\r\n defaultExpandedKeys: ['0-0', '0-1', '0-2'],\r\n parentNode: {}\r\n };\r\n this.onSelect = this.onSelect.bind(this);\r\n this.addNode = this.addNode.bind(this);\r\n this.clickFun = this.clickFun.bind(this);\r\n this.getNodeByKey = this.getNodeByKey.bind(this);\r\n this.parentNode = null\r\n }\r\n componentDidMount() {\r\n setTimeout(() => {\r\n this.setState({\r\n treeData: [{\r\n name: 'pNode 01',\r\n key: '0-0',\r\n children: [{\r\n name: 'leaf 0-0-0',\r\n key: '0-0-0'\r\n }, {\r\n name: 'leaf 0-0-1',\r\n key: '0-0-1'\r\n }]\r\n }, {\r\n name: 'pNode 02',\r\n key: '0-1',\r\n children: [{\r\n name: 'leaf 0-1-0',\r\n key: '0-1-0'\r\n }, {\r\n name: 'leaf 0-1-1',\r\n key: '0-1-1'\r\n }]\r\n }, {\r\n name: 'pNode 03',\r\n key: '0-2',\r\n isLeaf: true\r\n }, ],\r\n });\r\n }, 100);\r\n }\r\n /**\r\n * 增加节点\r\n * @param string prKey [父节点key]\r\n * @param object nodeItem [子节点信息]\r\n */\r\n addNode(prKey, nodeItem) {\r\n const data = this.state.treeData;\r\n let parNode;\r\n if (prKey) {\r\n // 如果prKey存在则搜索父节点进行添加\r\n parNode = this.getNodeByKey(data, prKey);\r\n //如果父节点存在的话,添加到父节点上\r\n if (parNode) {\r\n if (!parNode.children) {\r\n parNode.children = [];\r\n }\r\n // 如果key不存在就动态生成一个\r\n if (!nodeItem.key) {\r\n nodeItem.key = prKey + parNode.children.length + 1;\r\n }\r\n parNode.children.push(nodeItem);\r\n }\r\n } else {\r\n // 没有穿prKey添加到根下成为一级节点\r\n if (!nodeItem.key) {\r\n nodeItem.key = \"0-\" + data.length + 1;\r\n }\r\n data.push(nodeItem);\r\n }\r\n\r\n this.setState({\r\n data\r\n });\r\n }\r\n\r\n getNodeByKey(data, key) {\r\n if (!this.parentNode) {\r\n data.find(item => {\r\n if (item.key === key) {\r\n console.log('item.name---' + item.name)\r\n this.parentNode = item;\r\n return (true);\r\n } else if (item.children) {\r\n return this.getNodeByKey(item.children, key);\r\n\r\n }\r\n })\r\n }\r\n return this.parentNode;\r\n }\r\n\r\n\r\n\r\n onSelect(info) {\r\n console.log('selected', info);\r\n }\r\n /**\r\n * 点击button事件\r\n */\r\n clickFun() {\r\n let prKey, nodeItem;\r\n prKey = '0-1';\r\n nodeItem = {\r\n name: 'leaf 0-0-4'\r\n }\r\n this.addNode(prKey, nodeItem);\r\n }\r\n\r\n onDragEnter = (info) => {\r\n console.log(info);\r\n // expandedKeys 需要受控时设置\r\n // this.setState({\r\n // expandedKeys: info.expandedKeys,\r\n // });\r\n }\r\n onDrop = (info) => {\r\n console.log(info);\r\n const dropKey = info.node.props.eventKey;\r\n const dragKey = info.dragNode.props.eventKey;\r\n // const dragNodesKeys = info.dragNodesKeys;\r\n const loop = (data, key, callback) => {\r\n data.forEach((item, index, arr) => {\r\n if (item.key === key) {\r\n return callback(item, index, arr);\r\n }\r\n if (item.children) {\r\n return loop(item.children, key, callback);\r\n }\r\n });\r\n };\r\n const data = [...this.state.treeData];\r\n let dragObj;\r\n loop(data, dragKey, (item, index, arr) => {\r\n arr.splice(index, 1);\r\n dragObj = item;\r\n });\r\n if (info.dropToGap) {\r\n let ar;\r\n let i;\r\n loop(data, dropKey, (item, index, arr) => {\r\n ar = arr;\r\n i = index;\r\n });\r\n ar.splice(i, 0, dragObj);\r\n } else {\r\n loop(data, dropKey, (item) => {\r\n item.children = item.children || [];\r\n // where to insert 示例添加到尾部,可以是随意位置\r\n item.children.push(dragObj);\r\n });\r\n }\r\n this.setState({\r\n treeData: data,\r\n });\r\n }\r\n\r\n render() {\r\n const loop = data => data.map((item) => {\r\n if (item.children) {\r\n return <TreeNode title={item.name} key={item.key}>{loop(item.children)}</TreeNode>;\r\n }\r\n return <TreeNode title={item.name} key={item.key} isLeaf={item.isLeaf} disabled={item.key === '0-0-0'} />;\r\n });\r\n const treeNodes = loop(this.state.treeData);\r\n console.log('defaultKeys--' + this.state.defaultExpandedKeys);\r\n return (\r\n <div>\r\n <Button colors=\"primary\" onClick={this.clickFun}>增加节点</Button>\r\n <Tree \r\n className=\"myCls\"\r\n onSelect={this.onSelect} \r\n defaultExpandedKeys={this.state.defaultExpandedKeys} \r\n draggable\r\n onDragEnter={this.onDragEnter}\r\n onDrop={this.onDrop}>\r\n {treeNodes}\r\n </Tree>\r\n </div>\r\n );\r\n }\r\n};\r\n\r\nexport default Demo7", "desc": " 增加节点和拖拽组合使用示例" }, { "example": _react2['default'].createElement(Demo8, null), "title": " Tree 节点可编辑", "code": "/**\r\n *\r\n * @title Tree 节点可编辑\r\n * @description 鼠标移动到节点上点击编辑图标进行编辑。e.node.props.eventKey代表当前节点key值。editKey指当前操作的节点key\r\n */\r\n\r\n\r\nimport React, {\r\n\tComponent\r\n} from 'react';\r\n\r\n\n\n\r\nconst TreeNode = Tree.TreeNode;\r\n\r\nclass Demo8 extends Component {\r\n\tconstructor(props) {\r\n\t\tsuper(props);\r\n\r\n\t\tthis.state = {\r\n\t\t\ttreeData: [],\r\n\t\t\tisHover: \"\",\r\n\t\t\teditKey: \"\"\r\n\t\t};\r\n\r\n\t}\r\n\r\n\r\n\tonMouseEnter = (e) => {\r\n\t\tthis.setState({\r\n\t\t\tisHover: e.node.props.eventKey\r\n\t\t})\r\n\t}\r\n\tonMouseLeave = (e, treenode) => {\r\n\t\tthis.setState({\r\n\t\t\tisHover: \"\",\r\n\t\t\teditKey: \"\"\r\n\t\t})\r\n\r\n\t}\r\n\r\n\teditRender = (item) => {\r\n\t\tthis.setState({\r\n\t\t\teditKey: item.key\r\n\t\t});\r\n\t}\r\n\tnodechange = (item, value) => {\r\n\t\titem.name = value;\r\n\t}\r\n\trenderTreeTitle = (item) => {\r\n\t\tlet titleIcon, titleInfo;\r\n\t\t//编辑时input框\r\n\t\tif (this.state.editKey == item.key) {\r\n\t\t\ttitleInfo = <input type=\"text\" id=\"itemKey\" defaultValue={item.name} onChange={(e) => this.nodechange(item, e.target.value)} />\r\n\t\t} else {\r\n\t\t\ttitleInfo = <span className=\"title-middle\">{item.name}</span>\r\n\t\t}\r\n\t\t//编辑图标\r\n\t\tif (this.state.isHover == item.key) {\r\n\t\t\ttitleIcon = <Icon className=\"title-middle edit-icon\" type=\"uf-pencil\" onClick={(e) => this.editRender(item)}></Icon>;\r\n\t\t}\r\n\t\treturn (<div className=\"title-con\">\r\n\r\n\t\t\t{titleInfo}\r\n\t\t\t{titleIcon}\r\n\t\t</div>);\r\n\t}\r\n\r\n\tcomponentDidMount = () => {\r\n\t\tsetTimeout(() => {\r\n\t\t\tthis.setState({\r\n\t\t\t\ttreeData: [{\r\n\t\t\t\t\tname: 'pNode 01',\r\n\t\t\t\t\tkey: '0-0',\r\n\t\t\t\t\tchildren: [{\r\n\t\t\t\t\t\tname: 'leaf 0-0-0',\r\n\t\t\t\t\t\tkey: '0-0-0'\r\n\t\t\t\t\t}, {\r\n\t\t\t\t\t\tname: 'leaf 0-0-1',\r\n\t\t\t\t\t\tkey: '0-0-1'\r\n\t\t\t\t\t}]\r\n\t\t\t\t}, {\r\n\t\t\t\t\tname: 'pNode 02',\r\n\t\t\t\t\tkey: '0-1',\r\n\t\t\t\t\tchildren: [{\r\n\t\t\t\t\t\tname: 'leaf 0-1-0',\r\n\t\t\t\t\t\tkey: '0-1-0'\r\n\t\t\t\t\t}, {\r\n\t\t\t\t\t\tname: 'leaf 0-1-1',\r\n\t\t\t\t\t\tkey: '0-1-1'\r\n\t\t\t\t\t}]\r\n\t\t\t\t}, {\r\n\t\t\t\t\tname: 'pNode 03',\r\n\t\t\t\t\tkey: '0-2',\r\n\t\t\t\t\tisLeaf: true\r\n\t\t\t\t}, ],\r\n\t\t\t});\r\n\t\t\r\n\t\t}, 100);\r\n\t}\r\n\trender() {\r\n\t\tconst loop = data => data.map((item) => {\r\n\t\t\tif (item.children) {\r\n\t\t\t\treturn <TreeNode title={this.renderTreeTitle(item)} key={item.key}>{loop(item.children)}</TreeNode>;\r\n\t\t\t}\r\n\t\t\treturn <TreeNode title={this.renderTreeTitle(item)} key={item.key} isLeaf={item.isLeaf} disabled={item.key === '0-0-0'} />;\r\n\t\t});\r\n\t\tconst treeNodes = loop(this.state.treeData);\r\n\t\treturn (\r\n\t\t\t<Tree onMouseLeave={this.onMouseLeave} onMouseEnter={this.onMouseEnter} className=\"myCls\">\r\n\t\t\t\t{treeNodes}\r\n\t\t\t</Tree>\r\n\r\n\t\t);\r\n\t}\r\n}\r\n\r\n\r\n\r\nexport default Demo8;", "desc": " 鼠标移动到节点上点击编辑图标进行编辑。e.node.props.eventKey代表当前节点key值。editKey指当前操作的节点key", "scss_code": ".title-middle {\r\n display: inline-block;\r\n vertical-align: middle;\r\n}\r\n.edit-icon {\r\n float:right;\r\n font-size: 16px;\r\n height: 16px;\r\n line-height: 20px;\r\n}\r\n.title-con {\r\n min-width: 150px;\r\n}" }, { "example": _react2['default'].createElement(Demo9, null), "title": " 连接线Tree", "code": "/**\r\n *\r\n * @title 连接线Tree\r\n * @description \r\n *\r\n */\r\n\r\n\r\nimport React, {\r\n\tComponent\r\n} from 'react';\r\n\r\n\r\nconst TreeNode = Tree.TreeNode;\r\nclass Demo9 extends Component {\r\n\tconstructor(props) {\r\n\t\tsuper(props);\r\n\t\tconst keys = this.props.keys;\r\n\t\tthis.state = {\r\n\t\t\tdefaultExpandedKeys: keys\r\n\t\t};\r\n\r\n\t}\r\n\r\n\trender() {\r\n\t\treturn (\r\n\t\t\t<Tree className=\"myCls\" showLine checkable defaultExpandAll={true}>\r\n\t <TreeNode title=\"parent 1\" key=\"0-0\">\r\n\t <TreeNode title=\"parent 1-0\" key=\"0-0-0\" >\r\n\t <TreeNode title=\"leaf\" key=\"0-0-0-0\" />\r\n\t <TreeNode title=\"leaf\" key=\"0-0-0-1\" />\r\n\t </TreeNode>\r\n\t <TreeNode title=\"parent 1-1\" key=\"0-0-1\">\r\n\t <TreeNode title={<span>sss</span>} key=\"0-0-1-0\" />\r\n\t </TreeNode>\r\n\t </TreeNode>\r\n\t </Tree>\r\n\t\t);\r\n\t}\r\n}\r\n\r\nexport default Demo9;", "desc": " " }, { "example": _react2['default'].createElement(Demo10, null), "title": " Tree基本使用示例", "code": "/**\r\n *\r\n * @title Tree基本使用示例\r\n * @description 如何获取选中对象自定义对象和数据\r\n *\r\n */\r\n\r\n\r\nimport React, {\r\n\tComponent\r\n} from 'react';\r\n\r\n\r\nconst TreeNode = Tree.TreeNode;\r\n\r\nconst defaultProps = {\r\n\tkeys: ['0-0-0', '0-0-1']\r\n}\r\nclass Demo10 extends Component {\r\n\tconstructor(props) {\r\n\t\tsuper(props);\r\n\t\tconst keys = this.props.keys;\r\n\t\tthis.state = {\r\n\t\t\tdefaultExpandedKeys: keys,\r\n\t\t\tdefaultSelectedKeys: keys,\r\n\t\t\tdefaultCheckedKeys:keys\r\n\t\t\t// checkedKeys: {checked:keys},\r\n\t\t};\r\n }\r\n /**\r\n * 获取当前选中行的item对象。\r\n * @param {*} value \r\n */\r\n\tonSelect(selectedKeys, e) {\r\n console.log(`${selectedKeys} selected`);//获取key\r\n let currentObject = {};\r\n currentObject.title = e.node.props.title; //获取选中对象的数据\r\n currentObject.key = e.node.props.eventKey;\r\n console.log(currentObject); \r\n\t}\r\n\tonCheck = (checkedKeys) => {\r\n\t\tlet self = this;\r\n\t\tconsole.log('onCheck', checkedKeys);\r\n\t\tconst cks = {\r\n\t\t\tchecked: checkedKeys.checked || checkedKeys,\r\n\t\t};\r\n\t\t// this.setState({checkedKeys:cks});\r\n\t}\r\n\r\n\tonDoubleClick=(key,treeNode)=>{\r\n\t\tconsole.log('---onDblClick---'+key+'--treeNode--'+treeNode);\r\n\t}\r\n\trender() {\r\n\t\r\n\t\treturn (\r\n\t\t\t<Tree className=\"myCls\" showLine checkable\r\n defaultExpandedKeys={this.state.defaultExpandedKeys}\r\n defaultSelectedKeys={this.state.defaultSelectedKeys}\r\n defaultCheckedKeys = {this.state.defaultCheckedKeys}\r\n checkStrictly\r\n onSelect={this.onSelect} onCheck={this.onCheck}\r\n onDoubleClick={this.onDoubleClick}\r\n >\r\n <TreeNode title=\"parent 1\" key=\"0-0\" >\r\n <TreeNode title=\"parent 1-0\" key=\"0-0-0\" disabled>\r\n <TreeNode title=\"leaf\" key=\"0-0-0-0\" disableCheckbox />\r\n <TreeNode title=\"leaf\" key=\"0-0-0-1\" />\r\n </TreeNode>\r\n <TreeNode title=\"parent 1-1\" key=\"0-0-1\">\r\n <TreeNode title={<span>sss</span>} key=\"0-0-1-0\" />\r\n </TreeNode>\r\n <TreeNode title=\"parent 1-2\" key=\"0-0-2\" >\r\n <TreeNode title=\"leaf\" key=\"0-0-2-0\" />\r\n <TreeNode title=\"leaf\" key=\"0-0-2-1\" />\r\n </TreeNode>\r\n </TreeNode>\r\n\t </Tree>\r\n\t\t);\r\n\t}\r\n}\r\n\r\nDemo10.defaultProps = defaultProps;\r\n\r\n\r\nexport default Demo10;", "desc": " 如何获取选中对象自定义对象和数据" }, { "example": _react2['default'].createElement(Demo11, null), "title": " 用户自定义节点属性ext", "code": "/**\r\n*\r\n* @title 用户自定义节点属性ext\r\n* @description 业务中扩展的数据可以定义在ext属性中用户可以在TreeNode节点中获取ext属性。此例中将treeNode的数据存放在了ext中方便用户获取。\r\n* \b\r\n*/\r\n\r\nimport React, { Component } from 'react';\nimport { Tree } from 'tinper-bee';\r\n\r\n\r\nconst x = 6;\r\nconst y = 5;\r\nconst z = 2;\r\nconst gData = [];\r\n\r\nconst generateData = (_level, _preKey, _tns) => {\r\n const preKey = _preKey || '0';\r\n const tns = _tns || gData;\r\n\r\n const children = [];\r\n for (let i = 0; i < x; i++) {\r\n const key = `${preKey}-${i}`;\r\n tns.push({ title: key, key });\r\n if (i < y) {\r\n children.push(key);\r\n }\r\n }\r\n if (_level < 0) {\r\n return tns;\r\n }\r\n const level = _level - 1;\r\n children.forEach((key, index) => {\r\n tns[index].children = [];\r\n return generateData(level, key, tns[index].children);\r\n });\r\n};\r\ngenerateData(z);\r\n\r\nconst TreeNode = Tree.TreeNode;\r\n\r\n\r\nclass Demo11 extends Component{\r\n constructor(props) {\r\n \tsuper(props);\r\n this.state = {\r\n expandedKeys: [],\r\n autoExpandParent: true,\r\n checkedKeys: ['0-0-0'],\r\n selectedKeys: [],\r\n };\r\n this.onExpand = this.onExpand.bind(this);\r\n this.onCheck = this.onCheck.bind(this);\r\n this.onSelect = this.onSelect.bind(this);\r\n }\r\n onExpand(expandedKeys,nodeInfo) {\r\n console.log('onExpand---显示ext数据', nodeInfo.node.props.ext.data);\r\n\r\n this.setState({\r\n expandedKeys,\r\n autoExpandParent: false,\r\n });\r\n }\r\n onCheck(checkedKeys) {\r\n this.setState({\r\n checkedKeys,\r\n selectedKeys: ['0-3', '0-4'],\r\n });\r\n }\r\n onSelect(selectedKeys, info) {\r\n console.log('onSelect', info);\r\n this.setState({ selectedKeys });\r\n }\r\n // keydown的钩子事件\r\n onKeyDown = (e,treeNode)=>{\r\n console.log('***',e);\r\n return false;\r\n }\r\n render() {\r\n const loop = data => data.map((item) => {\r\n if (item.children) {\r\n return (\r\n <TreeNode key={item.key} title={item.key} disableCheckbox={item.key === '0-0-0'} ext={{'data':item}}>\r\n {loop(item.children)}\r\n </TreeNode>\r\n );\r\n }\r\n return <TreeNode key={item.key} title={item.key} isLeaf={true}/>;\r\n });\r\n return (\r\n <Tree\r\n checkable\r\n focusable\r\n className=\"demo2 myCls\"\r\n onExpand={this.onExpand} expandedKeys={this.state.expandedKeys}\r\n autoExpandParent={this.state.autoExpandParent}\r\n onCheck={this.onCheck} \r\n onSelect={this.onSelect} \r\n keyFun={this.onKeyDown}\r\n >\r\n {loop(gData)}\r\n </Tree>\r\n );\r\n }\r\n};\r\n\r\n\r\nexport default Demo11;", "desc": " 业务中扩展的数据可以定义在ext属性中用户可以在TreeNode节点中获取ext属性。此例中将treeNode的数据存放在了ext中方便用户获取。" }, { "example": _react2['default'].createElement(Demo12, null), "title": " 根据 treeData 数组渲染树节点", "code": "/**\r\n*\r\n* @title 根据 treeData 数组渲染树节点\r\n* @description 设置 treeData 属性,则不需要手动构造 TreeNode 节点key 在整个树范围内唯一)\r\n*/\r\n\r\nimport React, { Component } from 'react';\nimport { Tree } from 'tinper-bee';\r\n\r\n\r\nconst treeData = [\r\n {\r\n title: '0-0',\r\n key: '0-0',\r\n ext: '自定义属性',\r\n children: [\r\n {\r\n title: '0-0-0',\r\n key: '0-0-0',\r\n children: [\r\n { title: '0-0-0-0', key: '0-0-0-0' },\r\n { title: '0-0-0-1', key: '0-0-0-1' },\r\n { title: '0-0-0-2', key: '0-0-0-2' },\r\n ],\r\n },\r\n {\r\n title: '0-0-1',\r\n key: '0-0-1',\r\n children: [\r\n { title: '0-0-1-0', key: '0-0-1-0' },\r\n { title: '0-0-1-1', key: '0-0-1-1' },\r\n { title: '0-0-1-2', key: '0-0-1-2' },\r\n ],\r\n },\r\n {\r\n title: '0-0-2',\r\n key: '0-0-2',\r\n },\r\n ],\r\n },\r\n {\r\n title: '0-1',\r\n key: '0-1',\r\n children: [\r\n { title: '0-1-0-0', key: '0-1-0-0' },\r\n { title: '0-1-0-1', key: '0-1-0-1' },\r\n { title: '0-1-0-2', key: '0-1-0-2' },\r\n ],\r\n },\r\n {\r\n title: '0-2',\r\n key: '0-2',\r\n ext: '自定义属性'\r\n },\r\n];\r\n\r\nclass Demo12 extends Component {\r\n state = {\r\n expandedKeys: ['0-0-0', '0-0-1'],\r\n autoExpandParent: true,\r\n checkedKeys: ['0-0-0'],\r\n selectedKeys: [],\r\n };\r\n\r\n onExpand = expandedKeys => {\r\n console.log('onExpand', expandedKeys);\r\n // if not set autoExpandParent to false, if children expanded, parent can not collapse.\r\n // or, you can remove all expanded children keys.\r\n this.setState({\r\n expandedKeys,\r\n autoExpandParent: false,\r\n });\r\n };\r\n\r\n onCheck = checkedKeys => {\r\n console.log('onCheck', checkedKeys);\r\n this.setState({ checkedKeys });\r\n };\r\n\r\n onSelect = (selectedKeys, info) => {\r\n console.log('onSelect', info);\r\n this.setState({ selectedKeys });\r\n };\r\n\r\n render() {\r\n return (\r\n <Tree\r\n checkable\r\n treeData={treeData}\r\n onExpand={this.onExpand}\r\n expandedKeys={this.state.expandedKeys}\r\n autoExpandParent={this.state.autoExpandParent}\r\n onCheck={this.onCheck}\r\n checkedKeys={this.state.checkedKeys}\r\n onSelect={this.onSelect}\r\n selectedKeys={this.state.selectedKeys}\r\n />\r\n );\r\n }\r\n}\r\n\r\nexport default Demo12;", "desc": " 设置 treeData 属性,则不需要手动构造 TreeNode 节点key 在整个树范围内唯一)" }, { "example": _react2['default'].createElement(Demo13, null), "title": " 滚动加载树节点", "code": "/**\r\n*\r\n* @title 滚动加载树节点\r\n* @description 适用于大数据场景。注意:使用懒加载,需要通过 treeData 属性传入完整的数据结构,并设置 lazyLoad = {true}。可视区域的高度可以自定义,在 Tree 组件外层包裹一层div即可。\r\n*/\r\n\r\nimport React, { Component } from 'react';\nimport { Button, Tree } from 'tinper-bee';\r\n\n\r\n\r\nconst {TreeNode} = Tree;\r\n\r\nconst x = 1000;\r\nconst y = 1;\r\nconst z = 1;\r\nconst gData = [];\r\n\r\nconst generateData = (_level, _preKey, _tns) => {\r\n const preKey = _preKey || '0';\r\n const tns = _tns || gData;\r\n\r\n const children = [];\r\n for (let i = 0; i < x; i++) {\r\n const key = `${preKey}-${i}`;\r\n tns.push({ title: key, key });\r\n if (i < y) {\r\n children.push(key);\r\n }\r\n }\r\n if (_level < 0) {\r\n return tns;\r\n }\r\n const level = _level - 1;\r\n children.forEach((key, index) => {\r\n tns[index].children = [];\r\n return generateData(level, key, tns[index].children);\r\n });\r\n};\r\ngenerateData(z);\r\n\r\nconst data = [ ...new Array(10000) ].map((e, i) => {\r\n const rs = { key: i + 'a', title: i + 'a'};\r\n return rs;\r\n})\r\n\r\nclass Demo13 extends Component{\r\n constructor(props) {\r\n \tsuper(props);\r\n this.state = {\r\n expandedKeys: ['0-0','0-1','0-2','0-3', '0-4','0-5','0-6','0-0-0','0-0-1'],\r\n autoExpandParent: true,\r\n checkedKeys: ['0-0-0'],\r\n selectedKeys: [],\r\n treeData: data\r\n };\r\n this.onExpand = this.onExpand.bind(this);\r\n this.onCheck = this.onCheck.bind(this);\r\n this.onSelect = this.onSelect.bind(this);\r\n }\r\n onExpand(expandedKeys,nodeInfo) {\r\n // console.log('onExpand---显示ext数据', nodeInfo.node.props.ext.data);\r\n\r\n this.setState({\r\n expandedKeys,\r\n autoExpandParent: false,\r\n });\r\n }\r\n onCheck(checkedKeys) {\r\n this.setState({\r\n checkedKeys,\r\n selectedKeys: ['0-3', '0-4'],\r\n });\r\n }\r\n onSelect(selectedKeys, info) {\r\n console.log('onSelect', info);\r\n this.setState({ selectedKeys });\r\n }\r\n // keydown的钩子事件\r\n onKeyDown = (e,treeNode)=>{\r\n console.log('***',e);\r\n return false;\r\n }\r\n\r\n //使用 treeData 渲染树节点时,可使用该函数自定义节点显示内容(非必须)\r\n //注意isLeaf 属性是必传的,否则节点层级和展示会有问题\r\n renderTreeNodes = (data) => {\r\n const loop = data => data.map((item) => {\r\n if (item.children) {\r\n return (\r\n <TreeNode key={item.key} title={item.key} isLeaf={item.isLeaf}>\r\n {loop(item.children)}\r\n </TreeNode>\r\n );\r\n }\r\n return <TreeNode key={item.key} title={item.key} isLeaf={true}/>;\r\n });\r\n return loop(data);\r\n }\r\n\r\n changeTreeData = () => {\r\n this.setState({\r\n treeData: gData\r\n })\r\n }\r\n\r\n render() {\r\n return (\r\n <div>\r\n <Button onClick={this.changeTreeData}>改变数据源</Button>\r\n <div style={{height:'300px', overflow:'auto'}}>\r\n <Tree\r\n checkable\r\n focusable\r\n treeData={this.state.treeData}\r\n lazyLoad={true}\r\n debounceDuration={100}\r\n renderTreeNodes={this.renderTreeNodes}\r\n onExpand={this.onExpand}\r\n defaultExpandAll={true} \r\n expandedKeys={this.state.expandedKeys}\r\n autoExpandParent={this.state.autoExpandParent}\r\n onCheck={this.onCheck} \r\n onSelect={this.onSelect} \r\n keyFun={this.onKeyDown}\r\n >\r\n </Tree>\r\n </div>\r\n </div>\r\n );\r\n }\r\n};\r\n\r\n\r\nexport default Demo13;", "desc": " 适用于大数据场景。注意:使用懒加载,需要通过 treeData 属性传入完整的数据结构,并设置 lazyLoad = {true}。可视区域的高度可以自定义,在 Tree 组件外层包裹一层div即可。" }, { "example": _react2['default'].createElement(Demo14, null), "title": " 自定义滚动容器", "code": "/**\r\n*\r\n* @title 自定义滚动容器\r\n* @description 使用 getScrollParent 设置需要监听滚动事件的容器。\r\n*/\r\n\r\nimport React, { Component } from 'react';\nimport { Tree } from 'tinper-bee';\r\n\r\n\r\nconst {TreeNode} = Tree;\r\n\r\nconst x = 1000;\r\nconst y = 1;\r\nconst z = 1;\r\nconst gData = [];\r\n\r\nconst generateData = (_level, _preKey, _tns) => {\r\n const preKey = _preKey || '0';\r\n const tns = _tns || gData;\r\n\r\n const children = [];\r\n for (let i = 0; i < x; i++) {\r\n const key = `${preKey}-${i}`;\r\n tns.push({ title: key, key });\r\n if (i < y) {\r\n children.push(key);\r\n }\r\n }\r\n if (_level < 0) {\r\n return tns;\r\n }\r\n const level = _level - 1;\r\n children.forEach((key, index) => {\r\n tns[index].children = [];\r\n return generateData(level, key, tns[index].children);\r\n });\r\n};\r\ngenerateData(z);\r\n\r\nclass Demo14 extends Component{\r\n constructor(props) {\r\n \tsuper(props);\r\n this.state = {\r\n expandedKeys: ['0-0','0-1','0-2','0-3', '0-4','0-5','0-6','0-0-0','0-0-1'],\r\n autoExpandParent: true,\r\n checkedKeys: ['0-0-0'],\r\n selectedKeys: [],\r\n };\r\n this.onExpand = this.onExpand.bind(this);\r\n this.onCheck = this.onCheck.bind(this);\r\n this.onSelect = this.onSelect.bind(this);\r\n }\r\n onExpand(expandedKeys,nodeInfo) {\r\n // console.log('onExpand---显示ext数据', nodeInfo.node.props.ext.data);\r\n\r\n this.setState({\r\n expandedKeys,\r\n autoExpandParent: false,\r\n });\r\n }\r\n onCheck(checkedKeys) {\r\n this.setState({\r\n checkedKeys,\r\n selectedKeys: ['0-3', '0-4'],\r\n });\r\n }\r\n onSelect(selectedKeys, info) {\r\n console.log('onSelect', info);\r\n this.setState({ selectedKeys });\r\n }\r\n // keydown的钩子事件\r\n onKeyDown = (e,treeNode)=>{\r\n console.log('***',e);\r\n return false;\r\n }\r\n\r\n //使用 treeData 渲染树节点时,可使用该函数自定义节点显示内容(非必须)\r\n //注意isLeaf 属性是必传的,否则节点层级和展示会有问题\r\n renderTreeNodes = (data) => {\r\n const loop = data => data.map((item) => {\r\n if (item.children) {\r\n return (\r\n <TreeNode key={item.key} title={item.key} isLeaf={item.isLeaf}>\r\n {loop(item.children)}\r\n </TreeNode>\r\n );\r\n }\r\n return <TreeNode key={item.key} title={item.key} isLeaf={true}/>;\r\n });\r\n return loop(data);\r\n }\r\n\r\n render() {\r\n return (\r\n <div className=\"container\" style={{height:'300px', overflow:'auto'}}>\r\n <div>\r\n <Tree\r\n checkable\r\n focusable\r\n treeData={gData}\r\n lazyLoad={true}\r\n renderTreeNodes={this.renderTreeNodes}\r\n onExpand={this.onExpand}\r\n defaultExpandAll={true} \r\n expandedKeys={this.state.expandedKeys}\r\n autoExpandParent={this.state.autoExpandParent}\r\n onCheck={this.onCheck} \r\n onSelect={this.onSelect} \r\n keyFun={this.onKeyDown}\r\n getScrollContainer={() => {\r\n return document.querySelector('.container')\r\n }}\r\n >\r\n </Tree>\r\n </div>\r\n </div>\r\n );\r\n }\r\n};\r\n\r\n\r\nexport default Demo14;", "desc": " 使用 getScrollParent 设置需要监听滚动事件的容器。" }];
var Demo = function (_Component) {
_inherits(Demo, _Component);
function Demo(props) {
_classCallCheck(this, Demo);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.handleClick = function () {
_this.setState({ open: !_this.state.open });
};
_this.fCloseDrawer = function () {
_this.setState({
open: false
});
};
_this.state = {
open: false
};
return _this;
}
Demo.prototype.render = function render() {
var _props = this.props,
title = _props.title,
example = _props.example,
code = _props.code,
desc = _props.desc,
scss_code = _props.scss_code;
var header = _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'p',
{ className: 'component-title' },
title
),
_react2['default'].createElement(
'p',
null,
desc
),
_react2['default'].createElement(
'span',
{ className: 'component-code', onClick: this.handleClick },
' \u67E5\u770B\u6E90\u7801 ',
_react2['default'].createElement('i', { className: 'uf uf-arrow-right' }),
' '
)
);
return _react2['default'].createElement(
_beeLayout.Col,
{ md: 12, id: title.trim(), className: 'component-demo' },
_react2['default'].createElement(
_beePanel.Panel,
{ header: header },
example
),
_react2['default'].createElement(
_beeDrawer2['default'],
{ className: 'component-drawerc', title: title, show: this.state.open, placement: 'right', onClose: this.fCloseDrawer },
_react2['default'].createElement(
'div',
{ className: 'component-code-copy' },
' JS\u4EE3\u7801',
_react2['default'].createElement(_beeClipboard2['default'], { action: 'copy', text: code })
),
_react2['default'].createElement(
'pre',
{ className: 'pre-js' },
_react2['default'].createElement(
'code',
{ className: 'hljs javascript' },
code
)
),
!!scss_code ? _react2['default'].createElement(
'div',
{ className: 'component-code-copy copy-css' },
' SCSS\u4EE3\u7801',
_react2['default'].createElement(_beeClipboard2['default'], { action: 'copy', text: scss_code })
) : null,
!!scss_code ? _react2['default'].createElement(
'pre',
{ className: 'pre-css' },
_react2['default'].createElement(
'code',
{ className: 'hljs css' },
scss_code
)
) : null
)
);
};
return Demo;
}(_react.Component);
var DemoGroup = function (_Component2) {
_inherits(DemoGroup, _Component2);
function DemoGroup(props) {
_classCallCheck(this, DemoGroup);
return _possibleConstructorReturn(this, _Component2.call(this, props));
}
DemoGroup.prototype.render = function render() {
return _react2['default'].createElement(
_beeLayout.Row,
null,
DemoArray.map(function (child, index) {
return _react2['default'].createElement(Demo, { example: child.example, title: child.title, code: child.code, scss_code: child.scss_code, desc: child.desc, key: index });
})
);
};
return DemoGroup;
}(_react.Component);
_reactDom2['default'].render(_react2['default'].createElement(DemoGroup, null), document.getElementById('tinperBeeDemo'));
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = React;
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = ReactDOM;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Con = exports.Row = exports.Col = undefined;
var _Col2 = __webpack_require__(4);
var _Col3 = _interopRequireDefault(_Col2);
var _Row2 = __webpack_require__(7);
var _Row3 = _interopRequireDefault(_Row2);
var _Layout = __webpack_require__(8);
var _Layout2 = _interopRequireDefault(_Layout);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports.Col = _Col3["default"];
exports.Row = _Row3["default"];
exports.Con = _Layout2["default"];
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
componentClass: _propTypes2["default"].oneOfType([_propTypes2["default"].element, _propTypes2["default"].string]),
/**
* xs显示列数
*/
xs: _propTypes2["default"].number,
/**
* sm显示列数
*/
sm: _propTypes2["default"].number,
/**
* md显示列数
*/
md: _propTypes2["default"].number,
/**
* lg显示列数
*/
lg: _propTypes2["default"].number,
/**
* xs偏移列数
*/
xsOffset: _propTypes2["default"].number,
/**
* sm偏移列数
*/
smOffset: _propTypes2["default"].number,
/**
* md偏移列数
*/
mdOffset: _propTypes2["default"].number,
/**
* lg偏移列数
*/
lgOffset: _propTypes2["default"].number,
/**
* xs右偏移列数
*/
xsPush: _propTypes2["default"].number,
/**
* sm右偏移列数
*/
smPush: _propTypes2["default"].number,
/**
* md右偏移列数
*/
mdPush: _propTypes2["default"].number,
/**
* lg右偏移列数
*/
lgPush: _propTypes2["default"].number,
/**
* xs左偏移列数
*/
xsPull: _propTypes2["default"].number,
/**
* sm左偏移列数
*/
smPull: _propTypes2["default"].number,
/**
* md左偏移列数
*/
mdPull: _propTypes2["default"].number,
/**
* lg左偏移列数
*/
lgPull: _propTypes2["default"].number
};
var defaultProps = {
componentClass: 'div',
clsPrefix: 'u-col'
};
var DEVICE_SIZES = ['lg', 'md', 'sm', 'xs'];
var Col = function (_Component) {
_inherits(Col, _Component);
function Col() {
_classCallCheck(this, Col);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
Col.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
clsPrefix = _props.clsPrefix,
others = _objectWithoutProperties(_props, ['componentClass', 'className', 'clsPrefix']);
var tbClass = [];
/**
* 对传入props做样式转化
* @type {[type]}
*/
DEVICE_SIZES.forEach(function (size) {
function popProp(propSuffix, modifier) {
var propName = '' + size + propSuffix;
var propValue = others[propName];
if (propValue != undefined && propValue != null) {
tbClass.push(clsPrefix + '-' + size + modifier + '-' + propValue);
}
delete others[propName];
}
popProp('', '');
popProp('Offset', '-offset');
popProp('Push', '-push');
popProp('Pull', '-pull');
});
return _react2["default"].createElement(
Component,
_extends({
className: (0, _classnames2["default"])(tbClass, className)
}, others),
this.props.children
);
};
return Col;
}(_react.Component);
Col.defaultProps = defaultProps;
Col.propTypes = propTypes;
exports["default"] = Col;
module.exports = exports['default'];
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg) && arg.length) {
var inner = classNames.apply(null, arg);
if (inner) {
classes.push(inner);
}
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = PropTypes;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
componentClass: _propTypes2["default"].oneOfType([_propTypes2["default"].element, _propTypes2["default"].string])
};
var defaultProps = {
componentClass: 'div',
clsPrefix: 'u-row'
};
var Row = function (_Component) {
_inherits(Row, _Component);
function Row() {
_classCallCheck(this, Row);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
Row.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
clsPrefix = _props.clsPrefix,
className = _props.className,
others = _objectWithoutProperties(_props, ['componentClass', 'clsPrefix', 'className']);
var bsclass = '' + clsPrefix;
return _react2["default"].createElement(
Component,
_extends({}, others, {
className: (0, _classnames2["default"])(bsclass, className)
}),
this.props.children
);
};
return Row;
}(_react.Component);
Row.propTypes = propTypes;
Row.defaultProps = defaultProps;
exports["default"] = Row;
module.exports = exports['default'];
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
/**
* Adds `container-fluid` class.
*/
fluid: _propTypes2["default"].bool,
/**
* You can use a custom element for this component
*/
componentClass: _propTypes2["default"].oneOfType([_propTypes2["default"].element, _propTypes2["default"].string])
};
var defaultProps = {
componentClass: 'div',
fluid: false,
clsPrefix: 'u-container'
};
var Con = function (_React$Component) {
_inherits(Con, _React$Component);
function Con() {
_classCallCheck(this, Con);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Con.prototype.render = function render() {
var _tbclass;
var _props = this.props,
fluid = _props.fluid,
Component = _props.componentClass,
clsPrefix = _props.clsPrefix,
className = _props.className,
others = _objectWithoutProperties(_props, ['fluid', 'componentClass', 'clsPrefix', 'className']);
var tbclass = (_tbclass = {}, _defineProperty(_tbclass, '' + clsPrefix, !fluid), _defineProperty(_tbclass, clsPrefix + '-fluid', fluid), _tbclass);
return _react2["default"].createElement(
Component,
_extends({}, others, {
className: (0, _classnames2["default"])(tbclass, className)
}),
this.props.children
);
};
return Con;
}(_react2["default"].Component);
Con.propTypes = propTypes;
Con.defaultProps = defaultProps;
exports["default"] = Con;
module.exports = exports['default'];
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PanelGroup = exports.Panel = undefined;
var _Panel2 = __webpack_require__(10);
var _Panel3 = _interopRequireDefault(_Panel2);
var _PanelGroup2 = __webpack_require__(83);
var _PanelGroup3 = _interopRequireDefault(_PanelGroup2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports.Panel = _Panel3["default"];
exports.PanelGroup = _PanelGroup3["default"];
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _beeTransition = __webpack_require__(11);
var _beeMessage = __webpack_require__(65);
var _beeMessage2 = _interopRequireDefault(_beeMessage);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _copyToClipboard = __webpack_require__(81);
var _copyToClipboard2 = _interopRequireDefault(_copyToClipboard);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
//是否添加折叠
collapsible: _propTypes2["default"].bool,
onSelect: _propTypes2["default"].func,
//头部组件
header: _propTypes2["default"].node,
headerStyle: _propTypes2["default"].object,
id: _propTypes2["default"].oneOfType([_propTypes2["default"].string, _propTypes2["default"].number]),
headerContent: _propTypes2["default"].bool,
//footer组件
footer: _propTypes2["default"].node,
footerStyle: _propTypes2["default"].object,
//默认是否打开
defaultExpanded: _propTypes2["default"].bool,
//是否打开
expanded: _propTypes2["default"].bool,
//每个panel的标记
eventKey: _propTypes2["default"].any,
headerRole: _propTypes2["default"].string,
panelRole: _propTypes2["default"].string,
//颜色
colors: _propTypes2["default"].oneOf(['primary', 'accent', 'success', 'info', 'warning', 'danger', 'default', 'bordered']),
// From Collapse.的扩展动画
onEnter: _propTypes2["default"].func,
onEntering: _propTypes2["default"].func,
onEntered: _propTypes2["default"].func,
onExit: _propTypes2["default"].func,
onExiting: _propTypes2["default"].func,
onExited: _propTypes2["default"].func,
//是否可复制内容
copyable: _propTypes2["default"].bool
};
var defaultProps = {
defaultExpanded: false,
clsPrefix: "u-panel",
colors: "default"
};
var Panel = function (_React$Component) {
_inherits(Panel, _React$Component);
function Panel(props, context) {
_classCallCheck(this, Panel);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleClickTitle = _this.handleClickTitle.bind(_this);
_this.state = {
expanded: _this.props.defaultExpanded
};
return _this;
}
//头部点击事件
Panel.prototype.handleClickTitle = function handleClickTitle(e) {
// 不让事件进入事件池
e.persist();
e.selected = true;
if (this.props.onSelect) {
this.props.onSelect(this.props.eventKey, e);
} else {
e.preventDefault();
}
if (e.selected) {
this.setState({ expanded: !this.state.expanded });
}
};
//渲染panelheader
Panel.prototype.renderHeader = function renderHeader(collapsible, header, id, role, expanded, clsPrefix) {
var titleClassName = clsPrefix + '-title';
if (!collapsible) {
if (!_react2["default"].isValidElement(header)) {
return header;
}
return (0, _react.cloneElement)(header, {
className: (0, _classnames2["default"])(header.props.className, titleClassName)
});
}
if (!_react2["default"].isValidElement(header)) {
return _react2["default"].createElement(
'h4',
{ role: 'presentation', className: titleClassName },
this.renderAnchor(header, id, role, expanded)
);
}
if (this.props.headerContent) {
return (0, _react.cloneElement)(header, {
className: (0, _classnames2["default"])(header.props.className, titleClassName)
});
}
return (0, _react.cloneElement)(header, {
className: (0, _classnames2["default"])(header.props.className, titleClassName),
children: this.renderAnchor(header.props.children, id, role, expanded)
});
};
//如果使用链接渲染为a标签
Panel.prototype.renderAnchor = function renderAnchor(header, id, role, expanded) {
return _react2["default"].createElement(
'a',
{
role: role,
href: id && '#' + id,
'aria-controls': id,
'aria-expanded': expanded,
'aria-selected': expanded,
className: expanded ? null : 'collapsed'
},
header
);
};
//复制代码,弹出提示信息
Panel.prototype.copyDemo = function copyDemo(e) {
var panelTarget = e.target.parentNode;
var clipBoardContent = panelTarget.firstChild.innerText;
(0, _copyToClipboard2["default"])(clipBoardContent);
_beeMessage2["default"].create({ content: '复制成功!', color: 'success', duration: 2 });
};
//如果有折叠动画,渲染折叠动画
Panel.prototype.renderCollapsibleBody = function renderCollapsibleBody(id, expanded, role, children, clsPrefix, copyable, animationHooks) {
return _react2["default"].createElement(
_beeTransition.Collapse,
_extends({ 'in': expanded }, animationHooks),
_react2["default"].createElement(
'div',
{
id: id,
role: role,
className: clsPrefix + '-collapse',
'aria-hidden': !expanded
},
this.renderBody(children, clsPrefix, copyable)
)
);
};
//渲染panelbody
Panel.prototype.renderBody = function renderBody(rawChildren, clsPrefix, copyable) {
var self = this;
var children = [];
var bodyChildren = [];
var bodyClassName = clsPrefix + '-body';
//添加到body的children中
function maybeAddBody(self) {
if (!bodyChildren.length) {
return;
}
// 给子组件添加key为了之后触发事件时使用
children.push(_react2["default"].createElement(
'div',
{ key: children.length, className: bodyClassName },
bodyChildren,
copyable && _react2["default"].createElement('i', { className: clsPrefix + '-copy uf uf-files-o', onClick: self.copyDemo })
));
bodyChildren = [];
}
//转换为数组,方便复用
_react2["default"].Children.toArray(rawChildren).forEach(function (child) {
if (_react2["default"].isValidElement(child) && child.props.fill) {
maybeAddBody(self);
//将标示fill设置为undefined
children.push((0, _react.cloneElement)(child, { fill: undefined }));
return;
}
bodyChildren.push(child);
});
maybeAddBody(self);
return children;
};
Panel.prototype.render = function render() {
var _props = this.props,
collapsible = _props.collapsible,
header = _props.header,
id = _props.id,
footer = _props.footer,
propsExpanded = _props.expanded,
footerStyle = _props.footerStyle,
headerStyle = _props.headerStyle,
headerRole = _props.headerRole,
panelRole = _props.panelRole,
className = _props.className,
colors = _props.colors,
children = _props.children,
onEnter = _props.onEnter,
onEntering = _props.onEntering,
onEntered = _props.onEntered,
clsPrefix = _props.clsPrefix,
onExit = _props.onExit,
headerContent = _props.headerContent,
onExiting = _props.onExiting,
onExited = _props.onExited,
defaultExpanded = _props.defaultExpanded,
eventKey = _props.eventKey,
onSelect = _props.onSelect,
copyable = _props.copyable,
props = _objectWithoutProperties(_props, ['collapsible', 'header', 'id', 'footer', 'expanded', 'footerStyle', 'headerStyle', 'headerRole', 'panelRole', 'className', 'colors', 'children', 'onEnter', 'onEntering', 'onEntered', 'clsPrefix', 'onExit', 'headerContent', 'onExiting', 'onExited', 'defaultExpanded', 'eventKey', 'onSelect', 'copyable']);
var expanded = propsExpanded != null ? propsExpanded : this.state.expanded;
var classes = {};
classes['' + clsPrefix] = true;
classes[clsPrefix + '-' + colors] = true;
var headerClass = _defineProperty({}, clsPrefix + '-heading', true);
copyable === false ? false : true;
return _react2["default"].createElement(
'div',
_extends({}, props, {
className: (0, _classnames2["default"])(className, classes),
id: collapsible ? null : id
}),
header && _react2["default"].createElement(
'div',
{ className: (0, _classnames2["default"])(headerClass), style: headerStyle, onClick: this.handleClickTitle },
this.renderHeader(collapsible, header, id, headerRole, expanded, clsPrefix)
),
collapsible ? this.renderCollapsibleBody(id, expanded, panelRole, children, clsPrefix, copyable, { onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: onExited }) : this.renderBody(children, clsPrefix, copyable),
footer && _react2["default"].createElement(
'div',
{ className: clsPrefix + '-footer', style: footerStyle },
footer
)
);
};
return Panel;
}(_react2["default"].Component);
Panel.propTypes = propTypes;
Panel.defaultProps = defaultProps;
exports["default"] = Panel;
module.exports = exports['default'];
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Fade = exports.Collapse = exports.Transition = undefined;
var _Transition2 = __webpack_require__(12);
var _Transition3 = _interopRequireDefault(_Transition2);
var _Collapse2 = __webpack_require__(17);
var _Collapse3 = _interopRequireDefault(_Collapse2);
var _Fade2 = __webpack_require__(64);
var _Fade3 = _interopRequireDefault(_Fade2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports.Transition = _Transition3["default"];
exports.Collapse = _Collapse3["default"];
exports.Fade = _Fade3["default"];
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EXITING = exports.ENTERED = exports.ENTERING = exports.EXITED = exports.UNMOUNTED = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _properties = __webpack_require__(13);
var _properties2 = _interopRequireDefault(_properties);
var _on = __webpack_require__(16);
var _on2 = _interopRequireDefault(_on);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var transitionEndEvent = _properties2["default"].end;
//设置状态码
var UNMOUNTED = exports.UNMOUNTED = 0;
var EXITED = exports.EXITED = 1;
var ENTERING = exports.ENTERING = 2;
var ENTERED = exports.ENTERED = 3;
var EXITING = exports.EXITING = 4;
var propTypes = {
/**
* 是否触发动画
*/
"in": _propTypes2["default"].bool,
/**
* 不显示的时候是否移除组件
*/
unmountOnExit: _propTypes2["default"].bool,
/**
* 如果设置为默认显示,挂载时显示动画
*/
transitionAppear: _propTypes2["default"].bool,
/**
* 设置超时时间,防止出现问题,可设置为>=动画时间
*/
timeout: _propTypes2["default"].number,
/**
* 退出组件时添加的class
*/
exitedClassName: _propTypes2["default"].string,
/**
* 退出组件中添加的class
*/
exitingClassName: _propTypes2["default"].string,
/**
* 进入动画后添加的class
*/
enteredClassName: _propTypes2["default"].string,
/**
* 进入动画时添加的class
*/
enteringClassName: _propTypes2["default"].string,
/**
* 进入动画开始时的钩子函数
*/
onEnter: _propTypes2["default"].func,
/**
* 进入动画中的钩子函数
*/
onEntering: _propTypes2["default"].func,
/**
* 进入动画后的钩子函数
*/
onEntered: _propTypes2["default"].func,
/**
* 退出动画开始时的钩子函数
*/
onExit: _propTypes2["default"].func,
/**
* 退出动画中的钩子函数
*/
onExiting: _propTypes2["default"].func,
/**
* 退出动画后的钩子函数
*/
onExited: _propTypes2["default"].func
};
function noop() {}
var defaultProps = {
"in": false,
unmountOnExit: false,
transitionAppear: false,
timeout: 5000,
onEnter: noop,
onEntering: noop,
onEntered: noop,
onExit: noop,
onExiting: noop,
onExited: noop
};
/**
* 动画组件
*/
var Transition = function (_Component) {
_inherits(Transition, _Component);
function Transition(props, context) {
_classCallCheck(this, Transition);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
var initialStatus = void 0;
if (props["in"]) {
// 在componentdidmount时开始执行动画
initialStatus = props.transitionAppear ? EXITED : ENTERED;
} else {
initialStatus = props.unmountOnExit ? UNMOUNTED : EXITED;
}
_this.state = { status: initialStatus };
_this.nextCallback = null;
return _this;
}
Transition.prototype.componentDidMount = function componentDidMount() {
if (this.props.transitionAppear && this.props["in"]) {
this.performEnter(this.props);
}
};
Transition.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (nextProps["in"] && this.props.unmountOnExit) {
if (this.state.status === UNMOUNTED) {
// 在componentDidUpdate执行动画.
this.setState({ status: EXITED });
}
} else {
this._needsUpdate = true;
}
};
Transition.prototype.componentDidUpdate = function componentDidUpdate() {
var status = this.state.status;
if (this.props.unmountOnExit && status === EXITED) {
// 当使用unmountOnExit时exited为exiting和unmont的过渡状态
if (this.props["in"]) {
this.performEnter(this.props);
} else {
this.setState({ status: UNMOUNTED });
}
return;
}
// 确保只响应prop变化
if (this._needsUpdate) {
this._needsUpdate = false;
if (this.props["in"]) {
if (status === EXITING) {
this.performEnter(this.props);
} else if (status === EXITED) {
this.performEnter(this.props);
}
// 其他,当我们已经输入或输出
} else {
if (status === ENTERING || status === ENTERED) {
this.performExit(this.props);
}
// 我们已经输入或输出完成
}
}
};
Transition.prototype.componentWillUnmount = function componentWillUnmount() {
this.cancelNextCallback();
};
Transition.prototype.performEnter = function performEnter(props) {
var _this2 = this;
this.cancelNextCallback();
var node = _reactDom2["default"].findDOMNode(this);
// 这里接收新props
props.onEnter(node);
this.safeSetState({ status: ENTERING }, function () {
_this2.props.onEntering(node);
_this2.onTransitionEnd(node, function () {
_this2.safeSetState({ status: ENTERED }, function () {
_this2.props.onEntered(node);
});
});
});
};
Transition.prototype.performExit = function performExit(props) {
var _this3 = this;
this.cancelNextCallback();
var node = _reactDom2["default"].findDOMNode(this);
props.onExit(node);
this.safeSetState({ status: EXITING }, function () {
_this3.props.onExiting(node);
_this3.onTransitionEnd(node, function () {
_this3.safeSetState({ status: EXITED }, function () {
_this3.props.onExited(node);
});
});
});
};
Transition.prototype.cancelNextCallback = function cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
};
Transition.prototype.safeSetState = function safeSetState(nextState, callback) {
// 确保在组件销毁后挂起的setState被消除
this.setState(nextState, this.setNextCallback(callback));
};
Transition.prototype.setNextCallback = function setNextCallback(callback) {
var _this4 = this;
var active = true;
this.nextCallback = function (event) {
if (active) {
active = false;
_this4.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = function () {
active = false;
};
return this.nextCallback;
};
Transition.prototype.onTransitionEnd = function onTransitionEnd(node, handler) {
this.setNextCallback(handler);
if (node) {
if (transitionEndEvent == undefined) {
this.nextCallback();
} else {
(0, _on2["default"])(node, transitionEndEvent, this.nextCallback);
}
setTimeout(this.nextCallback, this.props.timeout);
} else {
setTimeout(this.nextCallback, 0);
}
};
Transition.prototype.render = function render() {
var status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
var _props = this.props,
children = _props.children,
className = _props.className,
childProps = _objectWithoutProperties(_props, ['children', 'className']);
Object.keys(Transition.propTypes).forEach(function (key) {
return delete childProps[key];
});
var transitionClassName = void 0;
if (status === EXITED) {
transitionClassName = this.props.exitedClassName;
} else if (status === ENTERING) {
transitionClassName = this.props.enteringClassName;
} else if (status === ENTERED) {
transitionClassName = this.props.enteredClassName;
} else if (status === EXITING) {
transitionClassName = this.props.exitingClassName;
}
var child = _react2["default"].Children.only(children);
return _react2["default"].cloneElement(child, _extends({}, childProps, {
className: (0, _classnames2["default"])(child.props.className, className, transitionClassName)
}));
};
return Transition;
}(_react.Component);
Transition.propTypes = propTypes;
Transition.defaultProps = defaultProps;
exports["default"] = Transition;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = exports.animationEnd = exports.animationDelay = exports.animationTiming = exports.animationDuration = exports.animationName = exports.transitionEnd = exports.transitionDuration = exports.transitionDelay = exports.transitionTiming = exports.transitionProperty = exports.transform = void 0;
var _inDOM = _interopRequireDefault(__webpack_require__(15));
var transform = 'transform';
exports.transform = transform;
var prefix, transitionEnd, animationEnd;
exports.animationEnd = animationEnd;
exports.transitionEnd = transitionEnd;
var transitionProperty, transitionDuration, transitionTiming, transitionDelay;
exports.transitionDelay = transitionDelay;
exports.transitionTiming = transitionTiming;
exports.transitionDuration = transitionDuration;
exports.transitionProperty = transitionProperty;
var animationName, animationDuration, animationTiming, animationDelay;
exports.animationDelay = animationDelay;
exports.animationTiming = animationTiming;
exports.animationDuration = animationDuration;
exports.animationName = animationName;
if (_inDOM.default) {
var _getTransitionPropert = getTransitionProperties();
prefix = _getTransitionPropert.prefix;
exports.transitionEnd = transitionEnd = _getTransitionPropert.transitionEnd;
exports.animationEnd = animationEnd = _getTransitionPropert.animationEnd;
exports.transform = transform = prefix + "-" + transform;
exports.transitionProperty = transitionProperty = prefix + "-transition-property";
exports.transitionDuration = transitionDuration = prefix + "-transition-duration";
exports.transitionDelay = transitionDelay = prefix + "-transition-delay";
exports.transitionTiming = transitionTiming = prefix + "-transition-timing-function";
exports.animationName = animationName = prefix + "-animation-name";
exports.animationDuration = animationDuration = prefix + "-animation-duration";
exports.animationTiming = animationTiming = prefix + "-animation-delay";
exports.animationDelay = animationDelay = prefix + "-animation-timing-function";
}
var _default = {
transform: transform,
end: transitionEnd,
property: transitionProperty,
timing: transitionTiming,
delay: transitionDelay,
duration: transitionDuration
};
exports.default = _default;
function getTransitionProperties() {
var style = document.createElement('div').style;
var vendorMap = {
O: function O(e) {
return "o" + e.toLowerCase();
},
Moz: function Moz(e) {
return e.toLowerCase();
},
Webkit: function Webkit(e) {
return "webkit" + e;
},
ms: function ms(e) {
return "MS" + e;
}
};
var vendors = Object.keys(vendorMap);
var transitionEnd, animationEnd;
var prefix = '';
for (var i = 0; i < vendors.length; i++) {
var vendor = vendors[i];
if (vendor + "TransitionProperty" in style) {
prefix = "-" + vendor.toLowerCase();
transitionEnd = vendorMap[vendor]('TransitionEnd');
animationEnd = vendorMap[vendor]('AnimationEnd');
break;
}
}
if (!transitionEnd && 'transitionProperty' in style) transitionEnd = 'transitionend';
if (!animationEnd && 'animationName' in style) animationEnd = 'animationend';
style = null;
return {
animationEnd: animationEnd,
transitionEnd: transitionEnd,
prefix: prefix
};
}
/***/ }),
/* 14 */
/***/ (function(module, exports) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
module.exports = _interopRequireDefault;
/***/ }),
/* 15 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _default = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
exports.default = _default;
module.exports = exports["default"];
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = void 0;
var _inDOM = _interopRequireDefault(__webpack_require__(15));
var on = function on() {};
if (_inDOM.default) {
on = function () {
if (document.addEventListener) return function (node, eventName, handler, capture) {
return node.addEventListener(eventName, handler, capture || false);
};else if (document.attachEvent) return function (node, eventName, handler) {
return node.attachEvent('on' + eventName, function (e) {
e = e || window.event;
e.target = e.target || e.srcElement;
e.currentTarget = node;
handler.call(node, e);
});
};
}();
}
var _default = on;
exports.default = _default;
module.exports = exports["default"];
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _style = __webpack_require__(18);
var _style2 = _interopRequireDefault(_style);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _Transition = __webpack_require__(12);
var _Transition2 = _interopRequireDefault(_Transition);
var _capitalize = __webpack_require__(26);
var _capitalize2 = _interopRequireDefault(_capitalize);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var MARGINS = {
height: ['marginTop', 'marginBottom'],
width: ['marginLeft', 'marginRight']
};
// reading a dimension prop will cause the browser to recalculate,
// which will let our animations work
function triggerBrowserReflow(node) {
node.offsetHeight; // eslint-disable-line no-unused-expressions
}
function getDimensionValue(dimension, elem) {
var value = elem['offset' + (0, _capitalize2["default"])(dimension)];
var margins = MARGINS[dimension];
return value + parseInt((0, _style2["default"])(elem, margins[0]), 10) + parseInt((0, _style2["default"])(elem, margins[1]), 10);
}
var propTypes = {
/**
* Show the component; triggers the expand or collapse animation
*/
"in": _propTypes2["default"].bool,
/**
* Unmount the component (remove it from the DOM) when it is collapsed
*/
unmountOnExit: _propTypes2["default"].bool,
/**
* Run the expand animation when the component mounts, if it is initially
* shown
*/
transitionAppear: _propTypes2["default"].bool,
/**
* Duration of the collapse animation in milliseconds, to ensure that
* finishing callbacks are fired even if the original browser transition end
* events are canceled
*/
timeout: _propTypes2["default"].number,
/**
* Callback fired before the component expands
*/
onEnter: _propTypes2["default"].func,
/**
* Callback fired after the component starts to expand
*/
onEntering: _propTypes2["default"].func,
/**
* Callback fired after the component has expanded
*/
onEntered: _propTypes2["default"].func,
/**
* Callback fired before the component collapses
*/
onExit: _propTypes2["default"].func,
/**
* Callback fired after the component starts to collapse
*/
onExiting: _propTypes2["default"].func,
/**
* Callback fired after the component has collapsed
*/
onExited: _propTypes2["default"].func,
/**
* The dimension used when collapsing, or a function that returns the
* dimension
*
* _Note: Bootstrap only partially supports 'width'!
* You will need to supply your own CSS animation for the `.width` CSS class._
*/
dimension: _propTypes2["default"].oneOfType([_propTypes2["default"].oneOf(['height', 'width']), _propTypes2["default"].func]),
/**
* Function that returns the height or width of the animating DOM node
*
* Allows for providing some custom logic for how much the Collapse component
* should animate in its specified dimension. Called with the current
* dimension prop value and the DOM node.
*/
getDimensionValue: _propTypes2["default"].func,
/**
* ARIA role of collapsible element
*/
role: _propTypes2["default"].string
};
var defaultProps = {
"in": false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false,
dimension: 'height',
getDimensionValue: getDimensionValue
};
var Collapse = function (_React$Component) {
_inherits(Collapse, _React$Component);
function Collapse(props, context) {
_classCallCheck(this, Collapse);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleEnter = _this.handleEnter.bind(_this);
_this.handleEntering = _this.handleEntering.bind(_this);
_this.handleEntered = _this.handleEntered.bind(_this);
_this.handleExit = _this.handleExit.bind(_this);
_this.handleExiting = _this.handleExiting.bind(_this);
return _this;
}
/* -- Expanding -- */
Collapse.prototype.handleEnter = function handleEnter(elem) {
var dimension = this._dimension();
elem.style[dimension] = '0';
};
Collapse.prototype.handleEntering = function handleEntering(elem) {
var dimension = this._dimension();
elem.style[dimension] = this._getScrollDimensionValue(elem, dimension);
};
Collapse.prototype.handleEntered = function handleEntered(elem) {
var dimension = this._dimension();
elem.style[dimension] = null;
};
/* -- Collapsing -- */
Collapse.prototype.handleExit = function handleExit(elem) {
var dimension = this._dimension();
elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px';
triggerBrowserReflow(elem);
};
Collapse.prototype.handleExiting = function handleExiting(elem) {
var dimension = this._dimension();
elem.style[dimension] = '0';
};
Collapse.prototype._dimension = function _dimension() {
return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension;
};
// for testing
Collapse.prototype._getScrollDimensionValue = function _getScrollDimensionValue(elem, dimension) {
return elem['scroll' + (0, _capitalize2["default"])(dimension)] + 'px';
};
Collapse.prototype.render = function render() {
var _props = this.props,
onEnter = _props.onEnter,
onEntering = _props.onEntering,
onEntered = _props.onEntered,
onExit = _props.onExit,
onExiting = _props.onExiting,
className = _props.className,
props = _objectWithoutProperties(_props, ['onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'className']);
delete props.dimension;
delete props.getDimensionValue;
var handleEnter = (0, _tinperBeeCore.createChainedFunction)(this.handleEnter, onEnter);
var handleEntering = (0, _tinperBeeCore.createChainedFunction)(this.handleEntering, onEntering);
var handleEntered = (0, _tinperBeeCore.createChainedFunction)(this.handleEntered, onEntered);
var handleExit = (0, _tinperBeeCore.createChainedFunction)(this.handleExit, onExit);
var handleExiting = (0, _tinperBeeCore.createChainedFunction)(this.handleExiting, onExiting);
var classes = {
width: this._dimension() === 'width'
};
return _react2["default"].createElement(_Transition2["default"], _extends({}, props, {
'aria-expanded': props.role ? props["in"] : null,
className: (0, _classnames2["default"])(className, classes),
exitedClassName: 'collapse',
exitingClassName: 'collapsing',
enteredClassName: 'collapse in',
enteringClassName: 'collapsing',
onEnter: handleEnter,
onEntering: handleEntering,
onEntered: handleEntered,
onExit: handleExit,
onExiting: handleExiting
}));
};
return Collapse;
}(_react2["default"].Component);
Collapse.propTypes = propTypes;
Collapse.defaultProps = defaultProps;
exports["default"] = Collapse;
module.exports = exports['default'];
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = style;
var _camelizeStyle = _interopRequireDefault(__webpack_require__(19));
var _hyphenateStyle = _interopRequireDefault(__webpack_require__(21));
var _getComputedStyle2 = _interopRequireDefault(__webpack_require__(23));
var _removeStyle = _interopRequireDefault(__webpack_require__(24));
var _properties = __webpack_require__(13);
var _isTransform = _interopRequireDefault(__webpack_require__(25));
function style(node, property, value) {
var css = '';
var transforms = '';
var props = property;
if (typeof property === 'string') {
if (value === undefined) {
return node.style[(0, _camelizeStyle.default)(property)] || (0, _getComputedStyle2.default)(node).getPropertyValue((0, _hyphenateStyle.default)(property));
} else {
(props = {})[property] = value;
}
}
Object.keys(props).forEach(function (key) {
var value = props[key];
if (!value && value !== 0) {
(0, _removeStyle.default)(node, (0, _hyphenateStyle.default)(key));
} else if ((0, _isTransform.default)(key)) {
transforms += key + "(" + value + ") ";
} else {
css += (0, _hyphenateStyle.default)(key) + ": " + value + ";";
}
});
if (transforms) {
css += _properties.transform + ": " + transforms + ";";
}
node.style.cssText += ';' + css;
}
module.exports = exports["default"];
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = camelizeStyleName;
var _camelize = _interopRequireDefault(__webpack_require__(20));
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
* https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js
*/
var msPattern = /^-ms-/;
function camelizeStyleName(string) {
return (0, _camelize.default)(string.replace(msPattern, 'ms-'));
}
module.exports = exports["default"];
/***/ }),
/* 20 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = camelize;
var rHyphen = /-(.)/g;
function camelize(string) {
return string.replace(rHyphen, function (_, chr) {
return chr.toUpperCase();
});
}
module.exports = exports["default"];
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = hyphenateStyleName;
var _hyphenate = _interopRequireDefault(__webpack_require__(22));
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
* https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js
*/
var msPattern = /^ms-/;
function hyphenateStyleName(string) {
return (0, _hyphenate.default)(string).replace(msPattern, '-ms-');
}
module.exports = exports["default"];
/***/ }),
/* 22 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = hyphenate;
var rUpper = /([A-Z])/g;
function hyphenate(string) {
return string.replace(rUpper, '-$1').toLowerCase();
}
module.exports = exports["default"];
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = _getComputedStyle;
var _camelizeStyle = _interopRequireDefault(__webpack_require__(19));
var rposition = /^(top|right|bottom|left)$/;
var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i;
function _getComputedStyle(node) {
if (!node) throw new TypeError('No Element passed to `getComputedStyle()`');
var doc = node.ownerDocument;
return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : {
//ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72
getPropertyValue: function getPropertyValue(prop) {
var style = node.style;
prop = (0, _camelizeStyle.default)(prop);
if (prop == 'float') prop = 'styleFloat';
var current = node.currentStyle[prop] || null;
if (current == null && style && style[prop]) current = style[prop];
if (rnumnonpx.test(current) && !rposition.test(prop)) {
// Remember the original values
var left = style.left;
var runStyle = node.runtimeStyle;
var rsLeft = runStyle && runStyle.left; // Put in the new values to get a computed value out
if (rsLeft) runStyle.left = node.currentStyle.left;
style.left = prop === 'fontSize' ? '1em' : current;
current = style.pixelLeft + 'px'; // Revert the changed values
style.left = left;
if (rsLeft) runStyle.left = rsLeft;
}
return current;
}
};
}
module.exports = exports["default"];
/***/ }),
/* 24 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = removeStyle;
function removeStyle(node, key) {
return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key);
}
module.exports = exports["default"];
/***/ }),
/* 25 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = isTransform;
var supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i;
function isTransform(property) {
return !!(property && supportedTransforms.test(property));
}
module.exports = exports["default"];
/***/ }),
/* 26 */
/***/ (function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = capitalize;
function capitalize(string) {
return "" + string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = exports["default"];
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.Align = exports.toArray = exports.cssAnimation = exports.addEventListener = exports.contains = exports.KeyCode = exports.createChainedFunction = exports.splitComponent = exports.isRequiredForA11y = exports.elementType = exports.deprecated = exports.componentOrElement = exports.all = undefined;
var _all2 = __webpack_require__(28);
var _all3 = _interopRequireDefault(_all2);
var _componentOrElement2 = __webpack_require__(30);
var _componentOrElement3 = _interopRequireDefault(_componentOrElement2);
var _deprecated2 = __webpack_require__(31);
var _deprecated3 = _interopRequireDefault(_deprecated2);
var _elementType2 = __webpack_require__(34);
var _elementType3 = _interopRequireDefault(_elementType2);
var _isRequiredForA11y2 = __webpack_require__(35);
var _isRequiredForA11y3 = _interopRequireDefault(_isRequiredForA11y2);
var _splitComponent2 = __webpack_require__(36);
var _splitComponent3 = _interopRequireDefault(_splitComponent2);
var _createChainedFunction2 = __webpack_require__(37);
var _createChainedFunction3 = _interopRequireDefault(_createChainedFunction2);
var _keyCode = __webpack_require__(38);
var _keyCode2 = _interopRequireDefault(_keyCode);
var _contains2 = __webpack_require__(39);
var _contains3 = _interopRequireDefault(_contains2);
var _addEventListener2 = __webpack_require__(40);
var _addEventListener3 = _interopRequireDefault(_addEventListener2);
var _cssAnimation2 = __webpack_require__(45);
var _cssAnimation3 = _interopRequireDefault(_cssAnimation2);
var _toArray2 = __webpack_require__(49);
var _toArray3 = _interopRequireDefault(_toArray2);
var _Align2 = __webpack_require__(50);
var _Align3 = _interopRequireDefault(_Align2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.all = _all3.default;
exports.componentOrElement = _componentOrElement3.default;
exports.deprecated = _deprecated3.default;
exports.elementType = _elementType3.default;
exports.isRequiredForA11y = _isRequiredForA11y3.default;
exports.splitComponent = _splitComponent3.default;
exports.createChainedFunction = _createChainedFunction3.default;
exports.KeyCode = _keyCode2.default;
exports.contains = _contains3.default;
exports.addEventListener = _addEventListener3.default;
exports.cssAnimation = _cssAnimation3.default;
exports.toArray = _toArray3.default;
//export getContainerRenderMixin from './getContainerRenderMixin';
exports.Align = _Align3.default;
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.default = all;
var _createChainableTypeChecker = __webpack_require__(29);
var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function all() {
for (var _len = arguments.length, validators = Array(_len), _key = 0; _key < _len; _key++) {
validators[_key] = arguments[_key];
}
function allPropTypes() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var error = null;
validators.forEach(function (validator) {
if (error != null) {
return;
}
var result = validator.apply(undefined, args);
if (result != null) {
error = result;
}
});
return error;
}
return (0, _createChainableTypeChecker2.default)(allPropTypes);
} /**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
/***/ }),
/* 29 */
/***/ (function(module, exports) {
'use strict';
exports.__esModule = true;
exports.default = createChainableTypeChecker;
/**
* 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.
*/
// Mostly taken from ReactPropTypes.
/* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
var componentNameSafe = componentName || '<<anonymous>>';
var propFullNameSafe = propFullName || propName;
if (props[propName] == null) {
if (isRequired) {
return new Error('Required ' + location + ' `' + propFullNameSafe + '` was not specified ' + ('in `' + componentNameSafe + '`.'));
}
return null;
}
for (var _len = arguments.length, args = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {
args[_key - 6] = arguments[_key];
}
return validate.apply(undefined, [props, propName, componentNameSafe, location, propFullNameSafe].concat(args));
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _createChainableTypeChecker = __webpack_require__(29);
var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue);
if (_react2.default.isValidElement(propValue)) {
return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement. You can usually obtain a ReactComponent or DOMElement ' + 'from a ReactElement by attaching a ref to it.');
}
if ((propType !== 'object' || typeof propValue.render !== 'function') && propValue.nodeType !== 1) {
return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement.');
}
return null;
}
exports.default = (0, _createChainableTypeChecker2.default)(validate);
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.default = deprecated;
var _warning = __webpack_require__(32);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var warned = {}; /**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
function deprecated(validator, reason) {
return function validate(props, propName, componentName, location, propFullName) {
var componentNameSafe = componentName || '<<anonymous>>';
var propFullNameSafe = propFullName || propName;
if (props[propName] != null) {
var messageKey = componentName + '.' + propName;
(0, _warning2.default)(warned[messageKey], 'The ' + location + ' `' + propFullNameSafe + '` of ' + ('`' + componentNameSafe + '` is deprecated. ' + reason + '.'));
warned[messageKey] = true;
}
for (var _len = arguments.length, args = Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {
args[_key - 5] = arguments[_key];
}
return validator.apply(undefined, [props, propName, componentName, location, propFullName].concat(args));
};
}
/* eslint-disable no-underscore-dangle */
function _resetWarned() {
warned = {};
}
deprecated._resetWarned = _resetWarned;
/* eslint-enable no-underscore-dangle */
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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';
/**
* 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 = function() {};
if (process.env.NODE_ENV !== 'production') {
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (format.length < 10 || (/^[s\W]*$/).test(format)) {
throw new Error(
'The warning format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: ' + format
);
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch(x) {}
}
};
}
module.exports = warning;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 33 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _createChainableTypeChecker = __webpack_require__(29);
var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function elementType(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue);
if (_react2.default.isValidElement(propValue)) {
return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).');
}
if (propType !== 'function' && propType !== 'string') {
return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).');
}
return null;
}
exports.default = (0, _createChainableTypeChecker2.default)(elementType);
/***/ }),
/* 35 */
/***/ (function(module, exports) {
'use strict';
exports.__esModule = true;
exports.default = isRequiredForA11y;
/**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
function isRequiredForA11y(validator) {
return function validate(props, propName, componentName, location, propFullName) {
var componentNameSafe = componentName || '<<anonymous>>';
var propFullNameSafe = propFullName || propName;
if (props[propName] == null) {
return new Error('The ' + location + ' `' + propFullNameSafe + '` is required to make ' + ('`' + componentNameSafe + '` accessible for users of assistive ') + 'technologies such as screen readers.');
}
for (var _len = arguments.length, args = Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {
args[_key - 5] = arguments[_key];
}
return validator.apply(undefined, [props, propName, componentName, location, propFullName].concat(args));
};
}
/***/ }),
/* 36 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = splitComponentProps;
/**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
function _objectEntries(obj) {
var entries = [];
var keys = Object.keys(obj);
for (var k = 0; k < keys.length; ++k) {
entries.push([keys[k], obj[keys[k]]]);
}return entries;
}
/**
* 分割要传入父元素和子元素的props
* @param {[object]} props 传入的属性
* @param {[reactElement]} Component 组件
* @return {[array]} 返回数组第一个元素为父元素props对象第二个子元素props对象
*/
function splitComponentProps(props, Component) {
var componentPropTypes = Component.propTypes;
var parentProps = {};
var childProps = {};
_objectEntries(props).forEach(function (_ref) {
var propName = _ref[0],
propValue = _ref[1];
if (componentPropTypes[propName]) {
parentProps[propName] = propValue;
} else {
childProps[propName] = propValue;
}
});
return [parentProps, childProps];
}
/***/ }),
/* 37 */
/***/ (function(module, exports) {
'use strict';
exports.__esModule = true;
/**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
function createChainedFunction() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return funcs.filter(function (f) {
return f != null;
}).reduce(function (acc, f) {
if (typeof f !== 'function') {
throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.');
}
if (acc === null) {
return f;
}
return function chainedFunction() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
acc.apply(this, args);
f.apply(this, args);
};
}, null);
}
exports.default = createChainedFunction;
/***/ }),
/* 38 */
/***/ (function(module, exports) {
/**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
'use strict';
/**
* @ignore
* some key-codes definition and utils from closure-library
* @author yiminghe@gmail.com
*/
var KeyCode = {
/**
* MAC_ENTER
*/
MAC_ENTER: 3,
/**
* BACKSPACE
*/
BACKSPACE: 8,
/**
* TAB
*/
TAB: 9,
/**
* NUMLOCK on FF/Safari Mac
*/
NUM_CENTER: 12, // NUMLOCK on FF/Safari Mac
/**
* ENTER
*/
ENTER: 13,
/**
* SHIFT
*/
SHIFT: 16,
/**
* CTRL
*/
CTRL: 17,
/**
* ALT
*/
ALT: 18,
/**
* PAUSE
*/
PAUSE: 19,
/**
* CAPS_LOCK
*/
CAPS_LOCK: 20,
/**
* ESC
*/
ESC: 27,
/**
* SPACE
*/
SPACE: 32,
/**
* PAGE_UP
*/
PAGE_UP: 33, // also NUM_NORTH_EAST
/**
* PAGE_DOWN
*/
PAGE_DOWN: 34, // also NUM_SOUTH_EAST
/**
* END
*/
END: 35, // also NUM_SOUTH_WEST
/**
* HOME
*/
HOME: 36, // also NUM_NORTH_WEST
/**
* LEFT
*/
LEFT: 37, // also NUM_WEST
/**
* UP
*/
UP: 38, // also NUM_NORTH
/**
* RIGHT
*/
RIGHT: 39, // also NUM_EAST
/**
* DOWN
*/
DOWN: 40, // also NUM_SOUTH
/**
* PRINT_SCREEN
*/
PRINT_SCREEN: 44,
/**
* INSERT
*/
INSERT: 45, // also NUM_INSERT
/**
* DELETE
*/
DELETE: 46, // also NUM_DELETE
/**
* ZERO
*/
ZERO: 48,
/**
* ONE
*/
ONE: 49,
/**
* TWO
*/
TWO: 50,
/**
* THREE
*/
THREE: 51,
/**
* FOUR
*/
FOUR: 52,
/**
* FIVE
*/
FIVE: 53,
/**
* SIX
*/
SIX: 54,
/**
* SEVEN
*/
SEVEN: 55,
/**
* EIGHT
*/
EIGHT: 56,
/**
* NINE
*/
NINE: 57,
/**
* QUESTION_MARK
*/
QUESTION_MARK: 63, // needs localization
/**
* A
*/
A: 65,
/**
* B
*/
B: 66,
/**
* C
*/
C: 67,
/**
* D
*/
D: 68,
/**
* E
*/
E: 69,
/**
* F
*/
F: 70,
/**
* G
*/
G: 71,
/**
* H
*/
H: 72,
/**
* I
*/
I: 73,
/**
* J
*/
J: 74,
/**
* K
*/
K: 75,
/**
* L
*/
L: 76,
/**
* M
*/
M: 77,
/**
* N
*/
N: 78,
/**
* O
*/
O: 79,
/**
* P
*/
P: 80,
/**
* Q
*/
Q: 81,
/**
* R
*/
R: 82,
/**
* S
*/
S: 83,
/**
* T
*/
T: 84,
/**
* U
*/
U: 85,
/**
* V
*/
V: 86,
/**
* W
*/
W: 87,
/**
* X
*/
X: 88,
/**
* Y
*/
Y: 89,
/**
* Z
*/
Z: 90,
/**
* META
*/
META: 91, // WIN_KEY_LEFT
/**
* WIN_KEY_RIGHT
*/
WIN_KEY_RIGHT: 92,
/**
* CONTEXT_MENU
*/
CONTEXT_MENU: 93,
/**
* NUM_ZERO
*/
NUM_ZERO: 96,
/**
* NUM_ONE
*/
NUM_ONE: 97,
/**
* NUM_TWO
*/
NUM_TWO: 98,
/**
* NUM_THREE
*/
NUM_THREE: 99,
/**
* NUM_FOUR
*/
NUM_FOUR: 100,
/**
* NUM_FIVE
*/
NUM_FIVE: 101,
/**
* NUM_SIX
*/
NUM_SIX: 102,
/**
* NUM_SEVEN
*/
NUM_SEVEN: 103,
/**
* NUM_EIGHT
*/
NUM_EIGHT: 104,
/**
* NUM_NINE
*/
NUM_NINE: 105,
/**
* NUM_MULTIPLY
*/
NUM_MULTIPLY: 106,
/**
* NUM_PLUS
*/
NUM_PLUS: 107,
/**
* NUM_MINUS
*/
NUM_MINUS: 109,
/**
* NUM_PERIOD
*/
NUM_PERIOD: 110,
/**
* NUM_DIVISION
*/
NUM_DIVISION: 111,
/**
* F1
*/
F1: 112,
/**
* F2
*/
F2: 113,
/**
* F3
*/
F3: 114,
/**
* F4
*/
F4: 115,
/**
* F5
*/
F5: 116,
/**
* F6
*/
F6: 117,
/**
* F7
*/
F7: 118,
/**
* F8
*/
F8: 119,
/**
* F9
*/
F9: 120,
/**
* F10
*/
F10: 121,
/**
* F11
*/
F11: 122,
/**
* F12
*/
F12: 123,
/**
* NUMLOCK
*/
NUMLOCK: 144,
/**
* SEMICOLON
*/
SEMICOLON: 186, // needs localization
/**
* DASH
*/
DASH: 189, // needs localization
/**
* EQUALS
*/
EQUALS: 187, // needs localization
/**
* COMMA
*/
COMMA: 188, // needs localization
/**
* PERIOD
*/
PERIOD: 190, // needs localization
/**
* SLASH
*/
SLASH: 191, // needs localization
/**
* APOSTROPHE
*/
APOSTROPHE: 192, // needs localization
/**
* SINGLE_QUOTE
*/
SINGLE_QUOTE: 222, // needs localization
/**
* OPEN_SQUARE_BRACKET
*/
OPEN_SQUARE_BRACKET: 219, // needs localization
/**
* BACKSLASH
*/
BACKSLASH: 220, // needs localization
/**
* CLOSE_SQUARE_BRACKET
*/
CLOSE_SQUARE_BRACKET: 221, // needs localization
/**
* WIN_KEY
*/
WIN_KEY: 224,
/**
* MAC_FF_META
*/
MAC_FF_META: 224, // Firefox (Gecko) fires this for the meta key instead of 91
/**
* WIN_IME
*/
WIN_IME: 229
};
/*
whether text and modified key is entered at the same time.
*/
KeyCode.isTextModifyingKeyEvent = function isTextModifyingKeyEvent(e) {
var keyCode = e.keyCode;
if (e.altKey && !e.ctrlKey || e.metaKey ||
// Function keys don't generate text
keyCode >= KeyCode.F1 && keyCode <= KeyCode.F12) {
return false;
}
// The following keys are quite harmless, even in combination with
// CTRL, ALT or SHIFT.
switch (keyCode) {
case KeyCode.ALT:
case KeyCode.CAPS_LOCK:
case KeyCode.CONTEXT_MENU:
case KeyCode.CTRL:
case KeyCode.DOWN:
case KeyCode.END:
case KeyCode.ESC:
case KeyCode.HOME:
case KeyCode.INSERT:
case KeyCode.LEFT:
case KeyCode.MAC_FF_META:
case KeyCode.META:
case KeyCode.NUMLOCK:
case KeyCode.NUM_CENTER:
case KeyCode.PAGE_DOWN:
case KeyCode.PAGE_UP:
case KeyCode.PAUSE:
case KeyCode.PRINT_SCREEN:
case KeyCode.RIGHT:
case KeyCode.SHIFT:
case KeyCode.UP:
case KeyCode.WIN_KEY:
case KeyCode.WIN_KEY_RIGHT:
return false;
default:
return true;
}
};
/*
whether character is entered.
*/
KeyCode.isCharacterKey = function isCharacterKey(keyCode) {
if (keyCode >= KeyCode.ZERO && keyCode <= KeyCode.NINE) {
return true;
}
if (keyCode >= KeyCode.NUM_ZERO && keyCode <= KeyCode.NUM_MULTIPLY) {
return true;
}
if (keyCode >= KeyCode.A && keyCode <= KeyCode.Z) {
return true;
}
// Safari sends zero key code for non-latin characters.
if (window.navigation.userAgent.indexOf('WebKit') !== -1 && keyCode === 0) {
return true;
}
switch (keyCode) {
case KeyCode.SPACE:
case KeyCode.QUESTION_MARK:
case KeyCode.NUM_PLUS:
case KeyCode.NUM_MINUS:
case KeyCode.NUM_PERIOD:
case KeyCode.NUM_DIVISION:
case KeyCode.SEMICOLON:
case KeyCode.DASH:
case KeyCode.EQUALS:
case KeyCode.COMMA:
case KeyCode.PERIOD:
case KeyCode.SLASH:
case KeyCode.APOSTROPHE:
case KeyCode.SINGLE_QUOTE:
case KeyCode.OPEN_SQUARE_BRACKET:
case KeyCode.BACKSLASH:
case KeyCode.CLOSE_SQUARE_BRACKET:
return true;
default:
return false;
}
};
module.exports = KeyCode;
/***/ }),
/* 39 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = contains;
/**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
function contains(root, n) {
var node = n;
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}
return false;
}
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.default = addEventListenerWrap;
var _addDomEventListener = __webpack_require__(41);
var _addDomEventListener2 = _interopRequireDefault(_addDomEventListener);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
function addEventListenerWrap(target, eventType, cb) {
/* eslint camelcase: 2 */
var callback = _reactDom2.default.unstable_batchedUpdates ? function run(e) {
_reactDom2.default.unstable_batchedUpdates(cb, e);
} : cb;
return (0, _addDomEventListener2.default)(target, eventType, callback);
}
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = addEventListener;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _EventObject = __webpack_require__(42);
var _EventObject2 = _interopRequireDefault(_EventObject);
function addEventListener(target, eventType, callback, option) {
function wrapCallback(e) {
var ne = new _EventObject2['default'](e);
callback.call(target, ne);
}
if (target.addEventListener) {
var _ret = (function () {
var useCapture = false;
if (typeof option === 'object') {
useCapture = option.capture || false;
} else if (typeof option === 'boolean') {
useCapture = option;
}
target.addEventListener(eventType, wrapCallback, option || false);
return {
v: {
remove: function remove() {
target.removeEventListener(eventType, wrapCallback, useCapture);
}
}
};
})();
if (typeof _ret === 'object') return _ret.v;
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, wrapCallback);
return {
remove: function remove() {
target.detachEvent('on' + eventType, wrapCallback);
}
};
}
}
module.exports = exports['default'];
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
/**
* @ignore
* event object for dom
* @author yiminghe@gmail.com
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _EventBaseObject = __webpack_require__(43);
var _EventBaseObject2 = _interopRequireDefault(_EventBaseObject);
var _objectAssign = __webpack_require__(44);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var TRUE = true;
var FALSE = false;
var commonProps = ['altKey', 'bubbles', 'cancelable', 'ctrlKey', 'currentTarget', 'eventPhase', 'metaKey', 'shiftKey', 'target', 'timeStamp', 'view', 'type'];
function isNullOrUndefined(w) {
return w === null || w === undefined;
}
var eventNormalizers = [{
reg: /^key/,
props: ['char', 'charCode', 'key', 'keyCode', 'which'],
fix: function fix(event, nativeEvent) {
if (isNullOrUndefined(event.which)) {
event.which = !isNullOrUndefined(nativeEvent.charCode) ? nativeEvent.charCode : nativeEvent.keyCode;
}
// add metaKey to non-Mac browsers (use ctrl for PC 's and Meta for Macs)
if (event.metaKey === undefined) {
event.metaKey = event.ctrlKey;
}
}
}, {
reg: /^touch/,
props: ['touches', 'changedTouches', 'targetTouches']
}, {
reg: /^hashchange$/,
props: ['newURL', 'oldURL']
}, {
reg: /^gesturechange$/i,
props: ['rotation', 'scale']
}, {
reg: /^(mousewheel|DOMMouseScroll)$/,
props: [],
fix: function fix(event, nativeEvent) {
var deltaX = undefined;
var deltaY = undefined;
var delta = undefined;
var wheelDelta = nativeEvent.wheelDelta;
var axis = nativeEvent.axis;
var wheelDeltaY = nativeEvent.wheelDeltaY;
var wheelDeltaX = nativeEvent.wheelDeltaX;
var detail = nativeEvent.detail;
// ie/webkit
if (wheelDelta) {
delta = wheelDelta / 120;
}
// gecko
if (detail) {
// press control e.detail == 1 else e.detail == 3
delta = 0 - (detail % 3 === 0 ? detail / 3 : detail);
}
// Gecko
if (axis !== undefined) {
if (axis === event.HORIZONTAL_AXIS) {
deltaY = 0;
deltaX = 0 - delta;
} else if (axis === event.VERTICAL_AXIS) {
deltaX = 0;
deltaY = delta;
}
}
// Webkit
if (wheelDeltaY !== undefined) {
deltaY = wheelDeltaY / 120;
}
if (wheelDeltaX !== undefined) {
deltaX = -1 * wheelDeltaX / 120;
}
// 默认 deltaY (ie)
if (!deltaX && !deltaY) {
deltaY = delta;
}
if (deltaX !== undefined) {
/**
* deltaX of mousewheel event
* @property deltaX
* @member Event.DomEvent.Object
*/
event.deltaX = deltaX;
}
if (deltaY !== undefined) {
/**
* deltaY of mousewheel event
* @property deltaY
* @member Event.DomEvent.Object
*/
event.deltaY = deltaY;
}
if (delta !== undefined) {
/**
* delta of mousewheel event
* @property delta
* @member Event.DomEvent.Object
*/
event.delta = delta;
}
}
}, {
reg: /^mouse|contextmenu|click|mspointer|(^DOMMouseScroll$)/i,
props: ['buttons', 'clientX', 'clientY', 'button', 'offsetX', 'relatedTarget', 'which', 'fromElement', 'toElement', 'offsetY', 'pageX', 'pageY', 'screenX', 'screenY'],
fix: function fix(event, nativeEvent) {
var eventDoc = undefined;
var doc = undefined;
var body = undefined;
var target = event.target;
var button = nativeEvent.button;
// Calculate pageX/Y if missing and clientX/Y available
if (target && isNullOrUndefined(event.pageX) && !isNullOrUndefined(nativeEvent.clientX)) {
eventDoc = target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = nativeEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = nativeEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// which for click: 1 === left; 2 === middle; 3 === right
// do not use button
if (!event.which && button !== undefined) {
if (button & 1) {
event.which = 1;
} else if (button & 2) {
event.which = 3;
} else if (button & 4) {
event.which = 2;
} else {
event.which = 0;
}
}
// add relatedTarget, if necessary
if (!event.relatedTarget && event.fromElement) {
event.relatedTarget = event.fromElement === target ? event.toElement : event.fromElement;
}
return event;
}
}];
function retTrue() {
return TRUE;
}
function retFalse() {
return FALSE;
}
function DomEventObject(nativeEvent) {
var type = nativeEvent.type;
var isNative = typeof nativeEvent.stopPropagation === 'function' || typeof nativeEvent.cancelBubble === 'boolean';
_EventBaseObject2['default'].call(this);
this.nativeEvent = nativeEvent;
// in case dom event has been mark as default prevented by lower dom node
var isDefaultPrevented = retFalse;
if ('defaultPrevented' in nativeEvent) {
isDefaultPrevented = nativeEvent.defaultPrevented ? retTrue : retFalse;
} else if ('getPreventDefault' in nativeEvent) {
// https://bugzilla.mozilla.org/show_bug.cgi?id=691151
isDefaultPrevented = nativeEvent.getPreventDefault() ? retTrue : retFalse;
} else if ('returnValue' in nativeEvent) {
isDefaultPrevented = nativeEvent.returnValue === FALSE ? retTrue : retFalse;
}
this.isDefaultPrevented = isDefaultPrevented;
var fixFns = [];
var fixFn = undefined;
var l = undefined;
var prop = undefined;
var props = commonProps.concat();
eventNormalizers.forEach(function (normalizer) {
if (type.match(normalizer.reg)) {
props = props.concat(normalizer.props);
if (normalizer.fix) {
fixFns.push(normalizer.fix);
}
}
});
l = props.length;
// clone properties of the original event object
while (l) {
prop = props[--l];
this[prop] = nativeEvent[prop];
}
// fix target property, if necessary
if (!this.target && isNative) {
this.target = nativeEvent.srcElement || document; // srcElement might not be defined either
}
// check if target is a text node (safari)
if (this.target && this.target.nodeType === 3) {
this.target = this.target.parentNode;
}
l = fixFns.length;
while (l) {
fixFn = fixFns[--l];
fixFn(this, nativeEvent);
}
this.timeStamp = nativeEvent.timeStamp || Date.now();
}
var EventBaseObjectProto = _EventBaseObject2['default'].prototype;
(0, _objectAssign2['default'])(DomEventObject.prototype, EventBaseObjectProto, {
constructor: DomEventObject,
preventDefault: function preventDefault() {
var e = this.nativeEvent;
// if preventDefault exists run it on the original event
if (e.preventDefault) {
e.preventDefault();
} else {
// otherwise set the returnValue property of the original event to FALSE (IE)
e.returnValue = FALSE;
}
EventBaseObjectProto.preventDefault.call(this);
},
stopPropagation: function stopPropagation() {
var e = this.nativeEvent;
// if stopPropagation exists run it on the original event
if (e.stopPropagation) {
e.stopPropagation();
} else {
// otherwise set the cancelBubble property of the original event to TRUE (IE)
e.cancelBubble = TRUE;
}
EventBaseObjectProto.stopPropagation.call(this);
}
});
exports['default'] = DomEventObject;
module.exports = exports['default'];
/***/ }),
/* 43 */
/***/ (function(module, exports) {
/**
* @ignore
* base event object for custom and dom event.
* @author yiminghe@gmail.com
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
function EventBaseObject() {
this.timeStamp = Date.now();
this.target = undefined;
this.currentTarget = undefined;
}
EventBaseObject.prototype = {
isEventObject: 1,
constructor: EventBaseObject,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function preventDefault() {
this.isDefaultPrevented = returnTrue;
},
stopPropagation: function stopPropagation() {
this.isPropagationStopped = returnTrue;
},
stopImmediatePropagation: function stopImmediatePropagation() {
this.isImmediatePropagationStopped = returnTrue;
// fixed 1.2
// call stopPropagation implicitly
this.stopPropagation();
},
halt: function halt(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
}
};
exports["default"] = EventBaseObject;
module.exports = exports["default"];
/***/ }),
/* 44 */
/***/ (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;
};
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
var _Event = __webpack_require__(46);
var _Event2 = _interopRequireDefault(_Event);
var _componentClasses = __webpack_require__(47);
var _componentClasses2 = _interopRequireDefault(_componentClasses);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isCssAnimationSupported = _Event2.default.endEvents.length !== 0;
var capitalPrefixes = ['Webkit', 'Moz', 'O',
// ms is special .... !
'ms'];
var prefixes = ['-webkit-', '-moz-', '-o-', 'ms-', ''];
function getStyleProperty(node, name) {
var style = window.getComputedStyle(node);
var ret = '';
for (var i = 0; i < prefixes.length; i++) {
ret = style.getPropertyValue(prefixes[i] + name);
if (ret) {
break;
}
}
return ret;
}
function fixBrowserByTimeout(node) {
if (isCssAnimationSupported) {
var transitionDelay = parseFloat(getStyleProperty(node, 'transition-delay')) || 0;
var transitionDuration = parseFloat(getStyleProperty(node, 'transition-duration')) || 0;
var animationDelay = parseFloat(getStyleProperty(node, 'animation-delay')) || 0;
var animationDuration = parseFloat(getStyleProperty(node, 'animation-duration')) || 0;
var time = Math.max(transitionDuration + transitionDelay, animationDuration + animationDelay);
// sometimes, browser bug
node.rcEndAnimTimeout = setTimeout(function () {
node.rcEndAnimTimeout = null;
if (node.rcEndListener) {
node.rcEndListener();
}
}, time * 1000 + 200);
}
}
function clearBrowserBugTimeout(node) {
if (node.rcEndAnimTimeout) {
clearTimeout(node.rcEndAnimTimeout);
node.rcEndAnimTimeout = null;
}
}
var cssAnimation = function cssAnimation(node, transitionName, endCallback) {
var nameIsObj = (typeof transitionName === 'undefined' ? 'undefined' : _typeof(transitionName)) === 'object';
var className = nameIsObj ? transitionName.name : transitionName;
var activeClassName = nameIsObj ? transitionName.active : transitionName + '-active';
var end = endCallback;
var start = void 0;
var active = void 0;
var nodeClasses = (0, _componentClasses2.default)(node);
if (endCallback && Object.prototype.toString.call(endCallback) === '[object Object]') {
end = endCallback.end;
start = endCallback.start;
active = endCallback.active;
}
if (node.rcEndListener) {
node.rcEndListener();
}
node.rcEndListener = function (e) {
if (e && e.target !== node) {
return;
}
if (node.rcAnimTimeout) {
clearTimeout(node.rcAnimTimeout);
node.rcAnimTimeout = null;
}
clearBrowserBugTimeout(node);
nodeClasses.remove(className);
nodeClasses.remove(activeClassName);
_Event2.default.removeEndEventListener(node, node.rcEndListener);
node.rcEndListener = null;
// Usually this optional end is used for informing an owner of
// a leave animation and telling it to remove the child.
if (end) {
end();
}
};
_Event2.default.addEndEventListener(node, node.rcEndListener);
if (start) {
start();
}
nodeClasses.add(className);
node.rcAnimTimeout = setTimeout(function () {
node.rcAnimTimeout = null;
nodeClasses.add(activeClassName);
if (active) {
setTimeout(active, 0);
}
fixBrowserByTimeout(node);
// 30ms for firefox
}, 30);
return {
stop: function stop() {
if (node.rcEndListener) {
node.rcEndListener();
}
}
};
};
cssAnimation.style = function (node, style, callback) {
if (node.rcEndListener) {
node.rcEndListener();
}
node.rcEndListener = function (e) {
if (e && e.target !== node) {
return;
}
if (node.rcAnimTimeout) {
clearTimeout(node.rcAnimTimeout);
node.rcAnimTimeout = null;
}
clearBrowserBugTimeout(node);
_Event2.default.removeEndEventListener(node, node.rcEndListener);
node.rcEndListener = null;
// Usually this optional callback is used for informing an owner of
// a leave animation and telling it to remove the child.
if (callback) {
callback();
}
};
_Event2.default.addEndEventListener(node, node.rcEndListener);
node.rcAnimTimeout = setTimeout(function () {
for (var s in style) {
if (style.hasOwnProperty(s)) {
node.style[s] = style[s];
}
}
node.rcAnimTimeout = null;
fixBrowserByTimeout(node);
}, 0);
};
cssAnimation.setTransition = function (node, p, value) {
var property = p;
var v = value;
if (value === undefined) {
v = property;
property = '';
}
property = property || '';
capitalPrefixes.forEach(function (prefix) {
node.style[prefix + 'Transition' + property] = v;
});
};
cssAnimation.isCssAnimationSupported = isCssAnimationSupported;
exports.default = cssAnimation;
/***/ }),
/* 46 */
/***/ (function(module, exports) {
'use strict';
exports.__esModule = true;
/**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
var EVENT_NAME_MAP = {
transitionend: {
transition: 'transitionend',
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'mozTransitionEnd',
OTransition: 'oTransitionEnd',
msTransition: 'MSTransitionEnd'
},
animationend: {
animation: 'animationend',
WebkitAnimation: 'webkitAnimationEnd',
MozAnimation: 'mozAnimationEnd',
OAnimation: 'oAnimationEnd',
msAnimation: 'MSAnimationEnd'
}
};
var endEvents = [];
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
if (EVENT_NAME_MAP.hasOwnProperty(baseEventName)) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
}
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
detectEvents();
}
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var TransitionEvents = {
addEndEventListener: function addEndEventListener(node, eventListener) {
if (endEvents.length === 0) {
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
endEvents: endEvents,
removeEndEventListener: function removeEndEventListener(node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
exports.default = TransitionEvents;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Module dependencies.
*/
try {
var index = __webpack_require__(48);
} catch (err) {
var index = __webpack_require__(48);
}
/**
* Whitespace regexp.
*/
var re = /\s+/;
/**
* toString reference.
*/
var toString = Object.prototype.toString;
/**
* Wrap `el` in a `ClassList`.
*
* @param {Element} el
* @return {ClassList}
* @api public
*/
module.exports = function(el){
return new ClassList(el);
};
/**
* Initialize a new ClassList for `el`.
*
* @param {Element} el
* @api private
*/
function ClassList(el) {
if (!el || !el.nodeType) {
throw new Error('A DOM element reference is required');
}
this.el = el;
this.list = el.classList;
}
/**
* Add class `name` if not already present.
*
* @param {String} name
* @return {ClassList}
* @api public
*/
ClassList.prototype.add = function(name){
// classList
if (this.list) {
this.list.add(name);
return this;
}
// fallback
var arr = this.array();
var i = index(arr, name);
if (!~i) arr.push(name);
this.el.className = arr.join(' ');
return this;
};
/**
* Remove class `name` when present, or
* pass a regular expression to remove
* any which match.
*
* @param {String|RegExp} name
* @return {ClassList}
* @api public
*/
ClassList.prototype.remove = function(name){
if ('[object RegExp]' == toString.call(name)) {
return this.removeMatching(name);
}
// classList
if (this.list) {
this.list.remove(name);
return this;
}
// fallback
var arr = this.array();
var i = index(arr, name);
if (~i) arr.splice(i, 1);
this.el.className = arr.join(' ');
return this;
};
/**
* Remove all classes matching `re`.
*
* @param {RegExp} re
* @return {ClassList}
* @api private
*/
ClassList.prototype.removeMatching = function(re){
var arr = this.array();
for (var i = 0; i < arr.length; i++) {
if (re.test(arr[i])) {
this.remove(arr[i]);
}
}
return this;
};
/**
* Toggle class `name`, can force state via `force`.
*
* For browsers that support classList, but do not support `force` yet,
* the mistake will be detected and corrected.
*
* @param {String} name
* @param {Boolean} force
* @return {ClassList}
* @api public
*/
ClassList.prototype.toggle = function(name, force){
// classList
if (this.list) {
if ("undefined" !== typeof force) {
if (force !== this.list.toggle(name, force)) {
this.list.toggle(name); // toggle again to correct
}
} else {
this.list.toggle(name);
}
return this;
}
// fallback
if ("undefined" !== typeof force) {
if (!force) {
this.remove(name);
} else {
this.add(name);
}
} else {
if (this.has(name)) {
this.remove(name);
} else {
this.add(name);
}
}
return this;
};
/**
* Return an array of classes.
*
* @return {Array}
* @api public
*/
ClassList.prototype.array = function(){
var className = this.el.getAttribute('class') || '';
var str = className.replace(/^\s+|\s+$/g, '');
var arr = str.split(re);
if ('' === arr[0]) arr.shift();
return arr;
};
/**
* Check if class `name` is present.
*
* @param {String} name
* @return {ClassList}
* @api public
*/
ClassList.prototype.has =
ClassList.prototype.contains = function(name){
return this.list
? this.list.contains(name)
: !! ~index(this.array(), name);
};
/***/ }),
/* 48 */
/***/ (function(module, exports) {
module.exports = function(arr, obj){
if (arr.indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.default = toArray;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toArray(children) {
var ret = [];
_react2.default.Children.forEach(children, function (c) {
ret.push(c);
});
return ret;
} /**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _domAlign = __webpack_require__(51);
var _domAlign2 = _interopRequireDefault(_domAlign);
var _addEventListener = __webpack_require__(40);
var _addEventListener2 = _interopRequireDefault(_addEventListener);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* This source code is quoted from rc-util.
* homepage: https://github.com/react-component/util
*/
//import isWindow from './isWindow';
function isWindow(obj) {
/* eslint no-eq-null: 0 */
/* eslint eqeqeq: 0 */
return obj != null && obj == obj.window;
}
function buffer(fn, ms) {
var timer = void 0;
function clear() {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
function bufferFn() {
clear();
timer = setTimeout(fn, ms);
}
bufferFn.clear = clear;
return bufferFn;
}
var propTypes = {
childrenProps: _propTypes2.default.object,
align: _propTypes2.default.object.isRequired,
target: _propTypes2.default.func,
onAlign: _propTypes2.default.func,
monitorBufferTime: _propTypes2.default.number,
monitorWindowResize: _propTypes2.default.bool,
disabled: _propTypes2.default.bool,
children: _propTypes2.default.any
};
var defaultProps = {
target: function target() {
return window;
},
onAlign: function onAlign() {},
monitorBufferTime: 50,
monitorWindowResize: false,
disabled: false
};
var Align = function (_React$Component) {
_inherits(Align, _React$Component);
function Align(props) {
_classCallCheck(this, Align);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_initialiseProps.call(_this);
return _this;
}
Align.prototype.componentDidMount = function componentDidMount() {
var props = this.props;
// if parent ref not attached .... use document.getElementById
this.forceAlign();
if (!props.disabled && props.monitorWindowResize) {
this.startMonitorWindowResize();
}
};
Align.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var reAlign = false;
var props = this.props;
if (!props.disabled) {
if (prevProps.disabled || prevProps.align !== props.align) {
reAlign = true;
} else {
var lastTarget = prevProps.target();
var currentTarget = props.target();
if (isWindow(lastTarget) && isWindow(currentTarget)) {
reAlign = false;
} else if (lastTarget !== currentTarget) {
reAlign = true;
}
}
}
if (reAlign) {
this.forceAlign();
}
if (props.monitorWindowResize && !props.disabled) {
this.startMonitorWindowResize();
} else {
this.stopMonitorWindowResize();
}
};
Align.prototype.componentWillUnmount = function componentWillUnmount() {
this.stopMonitorWindowResize();
};
Align.prototype.render = function render() {
var _props = this.props,
childrenProps = _props.childrenProps,
children = _props.children;
var child = _react2.default.Children.only(children);
if (childrenProps) {
var newProps = {};
for (var prop in childrenProps) {
if (childrenProps.hasOwnProperty(prop)) {
newProps[prop] = this.props[childrenProps[prop]];
}
}
return _react2.default.cloneElement(child, newProps);
}
return child;
};
return Align;
}(_react2.default.Component);
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.startMonitorWindowResize = function () {
if (!_this2.resizeHandler) {
_this2.bufferMonitor = buffer(_this2.forceAlign, _this2.props.monitorBufferTime);
_this2.resizeHandler = (0, _addEventListener2.default)(window, 'resize', _this2.bufferMonitor);
}
};
this.stopMonitorWindowResize = function () {
if (_this2.resizeHandler) {
_this2.bufferMonitor.clear();
_this2.resizeHandler.remove();
_this2.resizeHandler = null;
}
};
this.forceAlign = function () {
var props = _this2.props;
if (!props.disabled) {
var source = _reactDom2.default.findDOMNode(_this2);
props.onAlign(source, (0, _domAlign2.default)(source, props.target(), props.align));
}
};
};
;
Align.defaultProps = defaultProps;
Align.propTypes = propTypes;
exports.default = Align;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.alignPoint = exports.alignElement = undefined;
var _alignElement = __webpack_require__(52);
var _alignElement2 = _interopRequireDefault(_alignElement);
var _alignPoint = __webpack_require__(63);
var _alignPoint2 = _interopRequireDefault(_alignPoint);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
exports.alignElement = _alignElement2['default'];
exports.alignPoint = _alignPoint2['default'];
exports['default'] = _alignElement2['default'];
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _align = __webpack_require__(53);
var _align2 = _interopRequireDefault(_align);
var _getOffsetParent = __webpack_require__(57);
var _getOffsetParent2 = _interopRequireDefault(_getOffsetParent);
var _getVisibleRectForElement = __webpack_require__(56);
var _getVisibleRectForElement2 = _interopRequireDefault(_getVisibleRectForElement);
var _getRegion = __webpack_require__(60);
var _getRegion2 = _interopRequireDefault(_getRegion);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function isOutOfVisibleRect(target) {
var visibleRect = (0, _getVisibleRectForElement2['default'])(target);
var targetRegion = (0, _getRegion2['default'])(target);
return !visibleRect || targetRegion.left + targetRegion.width <= visibleRect.left || targetRegion.top + targetRegion.height <= visibleRect.top || targetRegion.left >= visibleRect.right || targetRegion.top >= visibleRect.bottom;
}
function alignElement(el, refNode, align) {
var target = align.target || refNode;
var refNodeRegion = (0, _getRegion2['default'])(target);
var isTargetNotOutOfVisible = !isOutOfVisibleRect(target);
return (0, _align2['default'])(el, refNodeRegion, align, isTargetNotOutOfVisible);
}
alignElement.__getOffsetParent = _getOffsetParent2['default'];
alignElement.__getVisibleRectForElement = _getVisibleRectForElement2['default'];
exports['default'] = alignElement;
module.exports = exports['default'];
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(54);
var _utils2 = _interopRequireDefault(_utils);
var _getVisibleRectForElement = __webpack_require__(56);
var _getVisibleRectForElement2 = _interopRequireDefault(_getVisibleRectForElement);
var _adjustForViewport = __webpack_require__(59);
var _adjustForViewport2 = _interopRequireDefault(_adjustForViewport);
var _getRegion = __webpack_require__(60);
var _getRegion2 = _interopRequireDefault(_getRegion);
var _getElFuturePos = __webpack_require__(61);
var _getElFuturePos2 = _interopRequireDefault(_getElFuturePos);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
// http://yiminghe.iteye.com/blog/1124720
function isFailX(elFuturePos, elRegion, visibleRect) {
return elFuturePos.left < visibleRect.left || elFuturePos.left + elRegion.width > visibleRect.right;
} /**
* align dom node flexibly
* @author yiminghe@gmail.com
*/
function isFailY(elFuturePos, elRegion, visibleRect) {
return elFuturePos.top < visibleRect.top || elFuturePos.top + elRegion.height > visibleRect.bottom;
}
function isCompleteFailX(elFuturePos, elRegion, visibleRect) {
return elFuturePos.left > visibleRect.right || elFuturePos.left + elRegion.width < visibleRect.left;
}
function isCompleteFailY(elFuturePos, elRegion, visibleRect) {
return elFuturePos.top > visibleRect.bottom || elFuturePos.top + elRegion.height < visibleRect.top;
}
function flip(points, reg, map) {
var ret = [];
_utils2['default'].each(points, function (p) {
ret.push(p.replace(reg, function (m) {
return map[m];
}));
});
return ret;
}
function flipOffset(offset, index) {
offset[index] = -offset[index];
return offset;
}
function convertOffset(str, offsetLen) {
var n = void 0;
if (/%$/.test(str)) {
n = parseInt(str.substring(0, str.length - 1), 10) / 100 * offsetLen;
} else {
n = parseInt(str, 10);
}
return n || 0;
}
function normalizeOffset(offset, el) {
offset[0] = convertOffset(offset[0], el.width);
offset[1] = convertOffset(offset[1], el.height);
}
/**
* @param el
* @param tgtRegion 参照节点所占的区域: { left, top, width, height }
* @param align
*/
function doAlign(el, tgtRegion, align, isTgtRegionVisible) {
var points = align.points;
var offset = align.offset || [0, 0];
var targetOffset = align.targetOffset || [0, 0];
var overflow = align.overflow;
var source = align.source || el;
offset = [].concat(offset);
targetOffset = [].concat(targetOffset);
overflow = overflow || {};
var newOverflowCfg = {};
var fail = 0;
// 当前节点可以被放置的显示区域
var visibleRect = (0, _getVisibleRectForElement2['default'])(source);
// 当前节点所占的区域, left/top/width/height
var elRegion = (0, _getRegion2['default'])(source);
// 将 offset 转换成数值,支持百分比
normalizeOffset(offset, elRegion);
normalizeOffset(targetOffset, tgtRegion);
// 当前节点将要被放置的位置
var elFuturePos = (0, _getElFuturePos2['default'])(elRegion, tgtRegion, points, offset, targetOffset);
// 当前节点将要所处的区域
var newElRegion = _utils2['default'].merge(elRegion, elFuturePos);
// 如果可视区域不能完全放置当前节点时允许调整
if (visibleRect && (overflow.adjustX || overflow.adjustY) && isTgtRegionVisible) {
if (overflow.adjustX) {
// 如果横向不能放下
if (isFailX(elFuturePos, elRegion, visibleRect)) {
// 对齐位置反下
var newPoints = flip(points, /[lr]/ig, {
l: 'r',
r: 'l'
});
// 偏移量也反下
var newOffset = flipOffset(offset, 0);
var newTargetOffset = flipOffset(targetOffset, 0);
var newElFuturePos = (0, _getElFuturePos2['default'])(elRegion, tgtRegion, newPoints, newOffset, newTargetOffset);
if (!isCompleteFailX(newElFuturePos, elRegion, visibleRect)) {
fail = 1;
points = newPoints;
offset = newOffset;
targetOffset = newTargetOffset;
}
}
}
if (overflow.adjustY) {
// 如果纵向不能放下
if (isFailY(elFuturePos, elRegion, visibleRect)) {
// 对齐位置反下
var _newPoints = flip(points, /[tb]/ig, {
t: 'b',
b: 't'
});
// 偏移量也反下
var _newOffset = flipOffset(offset, 1);
var _newTargetOffset = flipOffset(targetOffset, 1);
var _newElFuturePos = (0, _getElFuturePos2['default'])(elRegion, tgtRegion, _newPoints, _newOffset, _newTargetOffset);
if (!isCompleteFailY(_newElFuturePos, elRegion, visibleRect)) {
fail = 1;
points = _newPoints;
offset = _newOffset;
targetOffset = _newTargetOffset;
}
}
}
// 如果失败,重新计算当前节点将要被放置的位置
if (fail) {
elFuturePos = (0, _getElFuturePos2['default'])(elRegion, tgtRegion, points, offset, targetOffset);
_utils2['default'].mix(newElRegion, elFuturePos);
}
var isStillFailX = isFailX(elFuturePos, elRegion, visibleRect);
var isStillFailY = isFailY(elFuturePos, elRegion, visibleRect);
// 检查反下后的位置是否可以放下了,如果仍然放不下:
// 1. 复原修改过的定位参数
if (isStillFailX || isStillFailY) {
points = align.points;
offset = align.offset || [0, 0];
targetOffset = align.targetOffset || [0, 0];
}
// 2. 只有指定了可以调整当前方向才调整
newOverflowCfg.adjustX = overflow.adjustX && isStillFailX;
newOverflowCfg.adjustY = overflow.adjustY && isStillFailY;
// 确实要调整,甚至可能会调整高度宽度
if (newOverflowCfg.adjustX || newOverflowCfg.adjustY) {
newElRegion = (0, _adjustForViewport2['default'])(elFuturePos, elRegion, visibleRect, newOverflowCfg);
}
}
// need judge to in case set fixed with in css on height auto element
if (newElRegion.width !== elRegion.width) {
_utils2['default'].css(source, 'width', _utils2['default'].width(source) + newElRegion.width - elRegion.width);
}
if (newElRegion.height !== elRegion.height) {
_utils2['default'].css(source, 'height', _utils2['default'].height(source) + newElRegion.height - elRegion.height);
}
// https://github.com/kissyteam/kissy/issues/190
// 相对于屏幕位置没变,而 left/top 变了
// 例如 <div 'relative'><el absolute></div>
_utils2['default'].offset(source, {
left: newElRegion.left,
top: newElRegion.top
}, {
useCssRight: align.useCssRight,
useCssBottom: align.useCssBottom,
useCssTransform: align.useCssTransform,
ignoreShake: align.ignoreShake
});
return {
points: points,
offset: offset,
targetOffset: targetOffset,
overflow: newOverflowCfg
};
}
exports['default'] = doAlign;
/**
* 2012-04-26 yiminghe@gmail.com
* - 优化智能对齐算法
* - 慎用 resizeXX
*
* 2011-07-13 yiminghe@gmail.com note:
* - 增加智能对齐,以及大小调整选项
**/
module.exports = exports['default'];
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _propertyUtils = __webpack_require__(55);
var RE_NUM = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source;
var getComputedStyleX = void 0;
// https://stackoverflow.com/a/3485654/3040605
function forceRelayout(elem) {
var originalStyle = elem.style.display;
elem.style.display = 'none';
elem.offsetHeight; // eslint-disable-line
elem.style.display = originalStyle;
}
function css(el, name, v) {
var value = v;
if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') {
for (var i in name) {
if (name.hasOwnProperty(i)) {
css(el, i, name[i]);
}
}
return undefined;
}
if (typeof value !== 'undefined') {
if (typeof value === 'number') {
value = value + 'px';
}
el.style[name] = value;
return undefined;
}
return getComputedStyleX(el, name);
}
function getClientPosition(elem) {
var box = void 0;
var x = void 0;
var y = void 0;
var doc = elem.ownerDocument;
var body = doc.body;
var docElem = doc && doc.documentElement;
// 根据 GBS 最新数据A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式
box = elem.getBoundingClientRect();
// 注jQuery 还考虑减去 docElem.clientLeft/clientTop
// 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确
// 此外ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin
x = box.left;
y = box.top;
// In IE, most of the time, 2 extra pixels are added to the top and left
// due to the implicit 2-pixel inset border. In IE6/7 quirks mode and
// IE6 standards mode, this border can be overridden by setting the
// document element's border to zero -- thus, we cannot rely on the
// offset always being 2 pixels.
// In quirks mode, the offset can be determined by querying the body's
// clientLeft/clientTop, but in standards mode, it is found by querying
// the document element's clientLeft/clientTop. Since we already called
// getClientBoundingRect we have already forced a reflow, so it is not
// too expensive just to query them all.
// ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的
// 窗口边框标准是设 documentElement ,quirks 时设置 body
// 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去
// 但是非 ie 不可能设置窗口边框body html 也不是窗口 ,ie 可以通过 html,body 设置
// 标准 ie 下 docElem.clientTop 就是 border-top
// ie7 html 即窗口边框改变不了。永远为 2
// 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0
x -= docElem.clientLeft || body.clientLeft || 0;
y -= docElem.clientTop || body.clientTop || 0;
return {
left: x,
top: y
};
}
function getScroll(w, top) {
var ret = w['page' + (top ? 'Y' : 'X') + 'Offset'];
var method = 'scroll' + (top ? 'Top' : 'Left');
if (typeof ret !== 'number') {
var d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
}
return ret;
}
function getScrollLeft(w) {
return getScroll(w);
}
function getScrollTop(w) {
return getScroll(w, true);
}
function getOffset(el) {
var pos = getClientPosition(el);
var doc = el.ownerDocument;
var w = doc.defaultView || doc.parentWindow;
pos.left += getScrollLeft(w);
pos.top += getScrollTop(w);
return pos;
}
/**
* A crude way of determining if an object is a window
* @member util
*/
function isWindow(obj) {
// must use == for ie8
/* eslint eqeqeq:0 */
return obj !== null && obj !== undefined && obj == obj.window;
}
function getDocument(node) {
if (isWindow(node)) {
return node.document;
}
if (node.nodeType === 9) {
return node;
}
return node.ownerDocument;
}
function _getComputedStyle(elem, name, cs) {
var computedStyle = cs;
var val = '';
var d = getDocument(elem);
computedStyle = computedStyle || d.defaultView.getComputedStyle(elem, null);
// https://github.com/kissyteam/kissy/issues/61
if (computedStyle) {
val = computedStyle.getPropertyValue(name) || computedStyle[name];
}
return val;
}
var _RE_NUM_NO_PX = new RegExp('^(' + RE_NUM + ')(?!px)[a-z%]+$', 'i');
var RE_POS = /^(top|right|bottom|left)$/;
var CURRENT_STYLE = 'currentStyle';
var RUNTIME_STYLE = 'runtimeStyle';
var LEFT = 'left';
var PX = 'px';
function _getComputedStyleIE(elem, name) {
// currentStyle maybe null
// http://msdn.microsoft.com/en-us/library/ms535231.aspx
var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name];
// 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值
// 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19
// 在 ie 下不对,需要直接用 offset 方式
// borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// exclude left right for relativity
if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) {
// Remember the original values
var style = elem.style;
var left = style[LEFT];
var rsLeft = elem[RUNTIME_STYLE][LEFT];
// prevent flashing of content
elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT];
// Put in the new values to get a computed value out
style[LEFT] = name === 'fontSize' ? '1em' : ret || 0;
ret = style.pixelLeft + PX;
// Revert the changed values
style[LEFT] = left;
elem[RUNTIME_STYLE][LEFT] = rsLeft;
}
return ret === '' ? 'auto' : ret;
}
if (typeof window !== 'undefined') {
getComputedStyleX = window.getComputedStyle ? _getComputedStyle : _getComputedStyleIE;
}
function getOffsetDirection(dir, option) {
if (dir === 'left') {
return option.useCssRight ? 'right' : dir;
}
return option.useCssBottom ? 'bottom' : dir;
}
function oppositeOffsetDirection(dir) {
if (dir === 'left') {
return 'right';
} else if (dir === 'right') {
return 'left';
} else if (dir === 'top') {
return 'bottom';
} else if (dir === 'bottom') {
return 'top';
}
}
// 设置 elem 相对 elem.ownerDocument 的坐标
function setLeftTop(elem, offset, option) {
// set position first, in-case top/left are set even on static elem
if (css(elem, 'position') === 'static') {
elem.style.position = 'relative';
}
var presetH = -999;
var presetV = -999;
var horizontalProperty = getOffsetDirection('left', option);
var verticalProperty = getOffsetDirection('top', option);
var oppositeHorizontalProperty = oppositeOffsetDirection(horizontalProperty);
var oppositeVerticalProperty = oppositeOffsetDirection(verticalProperty);
if (horizontalProperty !== 'left') {
presetH = 999;
}
if (verticalProperty !== 'top') {
presetV = 999;
}
var originalTransition = '';
var originalOffset = getOffset(elem);
if ('left' in offset || 'top' in offset) {
originalTransition = (0, _propertyUtils.getTransitionProperty)(elem) || '';
(0, _propertyUtils.setTransitionProperty)(elem, 'none');
}
if ('left' in offset) {
elem.style[oppositeHorizontalProperty] = '';
elem.style[horizontalProperty] = presetH + 'px';
}
if ('top' in offset) {
elem.style[oppositeVerticalProperty] = '';
elem.style[verticalProperty] = presetV + 'px';
}
// force relayout
forceRelayout(elem);
var old = getOffset(elem);
var originalStyle = {};
for (var key in offset) {
if (offset.hasOwnProperty(key)) {
var dir = getOffsetDirection(key, option);
var preset = key === 'left' ? presetH : presetV;
var off = originalOffset[key] - old[key];
if (dir === key) {
originalStyle[dir] = preset + off;
} else {
originalStyle[dir] = preset - off;
}
}
}
css(elem, originalStyle);
// force relayout
forceRelayout(elem);
if ('left' in offset || 'top' in offset) {
(0, _propertyUtils.setTransitionProperty)(elem, originalTransition);
}
var ret = {};
for (var _key in offset) {
if (offset.hasOwnProperty(_key)) {
var _dir = getOffsetDirection(_key, option);
var _off = offset[_key] - originalOffset[_key];
if (_key === _dir) {
ret[_dir] = originalStyle[_dir] + _off;
} else {
ret[_dir] = originalStyle[_dir] - _off;
}
}
}
css(elem, ret);
}
function setTransform(elem, offset) {
var originalOffset = getOffset(elem);
var originalXY = (0, _propertyUtils.getTransformXY)(elem);
var resultXY = { x: originalXY.x, y: originalXY.y };
if ('left' in offset) {
resultXY.x = originalXY.x + offset.left - originalOffset.left;
}
if ('top' in offset) {
resultXY.y = originalXY.y + offset.top - originalOffset.top;
}
(0, _propertyUtils.setTransformXY)(elem, resultXY);
}
function setOffset(elem, offset, option) {
if (option.ignoreShake) {
var oriOffset = getOffset(elem);
var oLeft = oriOffset.left.toFixed(0);
var oTop = oriOffset.top.toFixed(0);
var tLeft = offset.left.toFixed(0);
var tTop = offset.top.toFixed(0);
if (oLeft === tLeft && oTop === tTop) {
return;
}
}
if (option.useCssRight || option.useCssBottom) {
setLeftTop(elem, offset, option);
} else if (option.useCssTransform && (0, _propertyUtils.getTransformName)() in document.body.style) {
setTransform(elem, offset, option);
} else {
setLeftTop(elem, offset, option);
}
}
function each(arr, fn) {
for (var i = 0; i < arr.length; i++) {
fn(arr[i]);
}
}
function isBorderBoxFn(elem) {
return getComputedStyleX(elem, 'boxSizing') === 'border-box';
}
var BOX_MODELS = ['margin', 'border', 'padding'];
var CONTENT_INDEX = -1;
var PADDING_INDEX = 2;
var BORDER_INDEX = 1;
var MARGIN_INDEX = 0;
function swap(elem, options, callback) {
var old = {};
var style = elem.style;
var name = void 0;
// Remember the old values, and insert the new ones
for (name in options) {
if (options.hasOwnProperty(name)) {
old[name] = style[name];
style[name] = options[name];
}
}
callback.call(elem);
// Revert the old values
for (name in options) {
if (options.hasOwnProperty(name)) {
style[name] = old[name];
}
}
}
function getPBMWidth(elem, props, which) {
var value = 0;
var prop = void 0;
var j = void 0;
var i = void 0;
for (j = 0; j < props.length; j++) {
prop = props[j];
if (prop) {
for (i = 0; i < which.length; i++) {
var cssProp = void 0;
if (prop === 'border') {
cssProp = '' + prop + which[i] + 'Width';
} else {
cssProp = prop + which[i];
}
value += parseFloat(getComputedStyleX(elem, cssProp)) || 0;
}
}
}
return value;
}
var domUtils = {};
each(['Width', 'Height'], function (name) {
domUtils['doc' + name] = function (refWin) {
var d = refWin.document;
return Math.max(
// firefox chrome documentElement.scrollHeight< body.scrollHeight
// ie standard mode : documentElement.scrollHeight> body.scrollHeight
d.documentElement['scroll' + name],
// quirks : documentElement.scrollHeight 最大等于可视窗口多一点?
d.body['scroll' + name], domUtils['viewport' + name](d));
};
domUtils['viewport' + name] = function (win) {
// pc browser includes scrollbar in window.innerWidth
var prop = 'client' + name;
var doc = win.document;
var body = doc.body;
var documentElement = doc.documentElement;
var documentElementProp = documentElement[prop];
// 标准模式取 documentElement
// backcompat 取 body
return doc.compatMode === 'CSS1Compat' && documentElementProp || body && body[prop] || documentElementProp;
};
});
/*
得到元素的大小信息
@param elem
@param name
@param {String} [extra] 'padding' : (css width) + padding
'border' : (css width) + padding + border
'margin' : (css width) + padding + border + margin
*/
function getWH(elem, name, ex) {
var extra = ex;
if (isWindow(elem)) {
return name === 'width' ? domUtils.viewportWidth(elem) : domUtils.viewportHeight(elem);
} else if (elem.nodeType === 9) {
return name === 'width' ? domUtils.docWidth(elem) : domUtils.docHeight(elem);
}
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
var borderBoxValue = name === 'width' ? elem.getBoundingClientRect().width : elem.getBoundingClientRect().height;
var computedStyle = getComputedStyleX(elem);
var isBorderBox = isBorderBoxFn(elem, computedStyle);
var cssBoxValue = 0;
if (borderBoxValue === null || borderBoxValue === undefined || borderBoxValue <= 0) {
borderBoxValue = undefined;
// Fall back to computed then un computed css if necessary
cssBoxValue = getComputedStyleX(elem, name);
if (cssBoxValue === null || cssBoxValue === undefined || Number(cssBoxValue) < 0) {
cssBoxValue = elem.style[name] || 0;
}
// Normalize '', auto, and prepare for extra
cssBoxValue = parseFloat(cssBoxValue) || 0;
}
if (extra === undefined) {
extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX;
}
var borderBoxValueOrIsBorderBox = borderBoxValue !== undefined || isBorderBox;
var val = borderBoxValue || cssBoxValue;
if (extra === CONTENT_INDEX) {
if (borderBoxValueOrIsBorderBox) {
return val - getPBMWidth(elem, ['border', 'padding'], which, computedStyle);
}
return cssBoxValue;
} else if (borderBoxValueOrIsBorderBox) {
if (extra === BORDER_INDEX) {
return val;
}
return val + (extra === PADDING_INDEX ? -getPBMWidth(elem, ['border'], which, computedStyle) : getPBMWidth(elem, ['margin'], which, computedStyle));
}
return cssBoxValue + getPBMWidth(elem, BOX_MODELS.slice(extra), which, computedStyle);
}
var cssShow = {
position: 'absolute',
visibility: 'hidden',
display: 'block'
};
// fix #119 : https://github.com/kissyteam/kissy/issues/119
function getWHIgnoreDisplay() {
for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) {
args[_key2] = arguments[_key2];
}
var val = void 0;
var elem = args[0];
// in case elem is window
// elem.offsetWidth === undefined
if (elem.offsetWidth !== 0) {
val = getWH.apply(undefined, args);
} else {
swap(elem, cssShow, function () {
val = getWH.apply(undefined, args);
});
}
return val;
}
each(['width', 'height'], function (name) {
var first = name.charAt(0).toUpperCase() + name.slice(1);
domUtils['outer' + first] = function (el, includeMargin) {
return el && getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX);
};
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
domUtils[name] = function (elem, v) {
var val = v;
if (val !== undefined) {
if (elem) {
var computedStyle = getComputedStyleX(elem);
var isBorderBox = isBorderBoxFn(elem);
if (isBorderBox) {
val += getPBMWidth(elem, ['padding', 'border'], which, computedStyle);
}
return css(elem, name, val);
}
return undefined;
}
return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX);
};
});
function mix(to, from) {
for (var i in from) {
if (from.hasOwnProperty(i)) {
to[i] = from[i];
}
}
return to;
}
var utils = {
getWindow: function getWindow(node) {
if (node && node.document && node.setTimeout) {
return node;
}
var doc = node.ownerDocument || node;
return doc.defaultView || doc.parentWindow;
},
getDocument: getDocument,
offset: function offset(el, value, option) {
if (typeof value !== 'undefined') {
setOffset(el, value, option || {});
} else {
return getOffset(el);
}
},
isWindow: isWindow,
each: each,
css: css,
clone: function clone(obj) {
var i = void 0;
var ret = {};
for (i in obj) {
if (obj.hasOwnProperty(i)) {
ret[i] = obj[i];
}
}
var overflow = obj.overflow;
if (overflow) {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
ret.overflow[i] = obj.overflow[i];
}
}
}
return ret;
},
mix: mix,
getWindowScrollLeft: function getWindowScrollLeft(w) {
return getScrollLeft(w);
},
getWindowScrollTop: function getWindowScrollTop(w) {
return getScrollTop(w);
},
merge: function merge() {
var ret = {};
for (var _len2 = arguments.length, args = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) {
args[_key3] = arguments[_key3];
}
for (var i = 0; i < args.length; i++) {
utils.mix(ret, args[i]);
}
return ret;
},
viewportWidth: 0,
viewportHeight: 0
};
mix(utils, domUtils);
exports['default'] = utils;
module.exports = exports['default'];
/***/ }),
/* 55 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getTransformName = getTransformName;
exports.setTransitionProperty = setTransitionProperty;
exports.getTransitionProperty = getTransitionProperty;
exports.getTransformXY = getTransformXY;
exports.setTransformXY = setTransformXY;
var vendorPrefix = void 0;
var jsCssMap = {
Webkit: '-webkit-',
Moz: '-moz-',
// IE did it wrong again ...
ms: '-ms-',
O: '-o-'
};
function getVendorPrefix() {
if (vendorPrefix !== undefined) {
return vendorPrefix;
}
vendorPrefix = '';
var style = document.createElement('p').style;
var testProp = 'Transform';
for (var key in jsCssMap) {
if (key + testProp in style) {
vendorPrefix = key;
}
}
return vendorPrefix;
}
function getTransitionName() {
return getVendorPrefix() ? getVendorPrefix() + 'TransitionProperty' : 'transitionProperty';
}
function getTransformName() {
return getVendorPrefix() ? getVendorPrefix() + 'Transform' : 'transform';
}
function setTransitionProperty(node, value) {
var name = getTransitionName();
if (name) {
node.style[name] = value;
if (name !== 'transitionProperty') {
node.style.transitionProperty = value;
}
}
}
function setTransform(node, value) {
var name = getTransformName();
if (name) {
node.style[name] = value;
if (name !== 'transform') {
node.style.transform = value;
}
}
}
function getTransitionProperty(node) {
return node.style.transitionProperty || node.style[getTransitionName()];
}
function getTransformXY(node) {
var style = window.getComputedStyle(node, null);
var transform = style.getPropertyValue('transform') || style.getPropertyValue(getTransformName());
if (transform && transform !== 'none') {
var matrix = transform.replace(/[^0-9\-.,]/g, '').split(',');
return { x: parseFloat(matrix[12] || matrix[4], 0), y: parseFloat(matrix[13] || matrix[5], 0) };
}
return {
x: 0,
y: 0
};
}
var matrix2d = /matrix\((.*)\)/;
var matrix3d = /matrix3d\((.*)\)/;
function setTransformXY(node, xy) {
var style = window.getComputedStyle(node, null);
var transform = style.getPropertyValue('transform') || style.getPropertyValue(getTransformName());
if (transform && transform !== 'none') {
var arr = void 0;
var match2d = transform.match(matrix2d);
if (match2d) {
match2d = match2d[1];
arr = match2d.split(',').map(function (item) {
return parseFloat(item, 10);
});
arr[4] = xy.x;
arr[5] = xy.y;
setTransform(node, 'matrix(' + arr.join(',') + ')');
} else {
var match3d = transform.match(matrix3d)[1];
arr = match3d.split(',').map(function (item) {
return parseFloat(item, 10);
});
arr[12] = xy.x;
arr[13] = xy.y;
setTransform(node, 'matrix3d(' + arr.join(',') + ')');
}
} else {
setTransform(node, 'translateX(' + xy.x + 'px) translateY(' + xy.y + 'px) translateZ(0)');
}
}
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(54);
var _utils2 = _interopRequireDefault(_utils);
var _getOffsetParent = __webpack_require__(57);
var _getOffsetParent2 = _interopRequireDefault(_getOffsetParent);
var _isAncestorFixed = __webpack_require__(58);
var _isAncestorFixed2 = _interopRequireDefault(_isAncestorFixed);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* 获得元素的显示部分的区域
*/
function getVisibleRectForElement(element) {
var visibleRect = {
left: 0,
right: Infinity,
top: 0,
bottom: Infinity
};
var el = (0, _getOffsetParent2['default'])(element);
var doc = _utils2['default'].getDocument(element);
var win = doc.defaultView || doc.parentWindow;
var body = doc.body;
var documentElement = doc.documentElement;
// Determine the size of the visible rect by climbing the dom accounting for
// all scrollable containers.
while (el) {
// clientWidth is zero for inline block elements in ie.
if ((navigator.userAgent.indexOf('MSIE') === -1 || el.clientWidth !== 0) &&
// body may have overflow set on it, yet we still get the entire
// viewport. In some browsers, el.offsetParent may be
// document.documentElement, so check for that too.
el !== body && el !== documentElement && _utils2['default'].css(el, 'overflow') !== 'visible') {
var pos = _utils2['default'].offset(el);
// add border
pos.left += el.clientLeft;
pos.top += el.clientTop;
visibleRect.top = Math.max(visibleRect.top, pos.top);
visibleRect.right = Math.min(visibleRect.right,
// consider area without scrollBar
pos.left + el.clientWidth);
visibleRect.bottom = Math.min(visibleRect.bottom, pos.top + el.clientHeight);
visibleRect.left = Math.max(visibleRect.left, pos.left);
} else if (el === body || el === documentElement) {
break;
}
el = (0, _getOffsetParent2['default'])(el);
}
// Set element position to fixed
// make sure absolute element itself don't affect it's visible area
// https://github.com/ant-design/ant-design/issues/7601
var originalPosition = null;
if (!_utils2['default'].isWindow(element) && element.nodeType !== 9) {
originalPosition = element.style.position;
var position = _utils2['default'].css(element, 'position');
if (position === 'absolute') {
element.style.position = 'fixed';
}
}
var scrollX = _utils2['default'].getWindowScrollLeft(win);
var scrollY = _utils2['default'].getWindowScrollTop(win);
var viewportWidth = _utils2['default'].viewportWidth(win);
var viewportHeight = _utils2['default'].viewportHeight(win);
var documentWidth = documentElement.scrollWidth;
var documentHeight = documentElement.scrollHeight;
// scrollXXX on html is sync with body which means overflow: hidden on body gets wrong scrollXXX.
// We should cut this ourself.
var bodyStyle = window.getComputedStyle(body);
if (bodyStyle.overflowX === 'hidden') {
documentWidth = win.innerWidth;
}
if (bodyStyle.overflowY === 'hidden') {
documentHeight = win.innerHeight;
}
// Reset element position after calculate the visible area
if (element.style) {
element.style.position = originalPosition;
}
if ((0, _isAncestorFixed2['default'])(element)) {
// Clip by viewport's size.
visibleRect.left = Math.max(visibleRect.left, scrollX);
visibleRect.top = Math.max(visibleRect.top, scrollY);
visibleRect.right = Math.min(visibleRect.right, scrollX + viewportWidth);
visibleRect.bottom = Math.min(visibleRect.bottom, scrollY + viewportHeight);
} else {
// Clip by document's size.
var maxVisibleWidth = Math.max(documentWidth, scrollX + viewportWidth);
visibleRect.right = Math.min(visibleRect.right, maxVisibleWidth);
var maxVisibleHeight = Math.max(documentHeight, scrollY + viewportHeight);
visibleRect.bottom = Math.min(visibleRect.bottom, maxVisibleHeight);
}
return visibleRect.top >= 0 && visibleRect.left >= 0 && visibleRect.bottom > visibleRect.top && visibleRect.right > visibleRect.left ? visibleRect : null;
}
exports['default'] = getVisibleRectForElement;
module.exports = exports['default'];
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(54);
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* 得到会导致元素显示不全的祖先元素
*/
function getOffsetParent(element) {
if (_utils2['default'].isWindow(element) || element.nodeType === 9) {
return null;
}
// ie 这个也不是完全可行
/*
<div style="width: 50px;height: 100px;overflow: hidden">
<div style="width: 50px;height: 100px;position: relative;" id="d6">
元素 6 高 100px 宽 50px<br/>
</div>
</div>
*/
// element.offsetParent does the right thing in ie7 and below. Return parent with layout!
// In other browsers it only includes elements with position absolute, relative or
// fixed, not elements with overflow set to auto or scroll.
// if (UA.ie && ieMode < 8) {
// return element.offsetParent;
// }
// 统一的 offsetParent 方法
var doc = _utils2['default'].getDocument(element);
var body = doc.body;
var parent = void 0;
var positionStyle = _utils2['default'].css(element, 'position');
var skipStatic = positionStyle === 'fixed' || positionStyle === 'absolute';
if (!skipStatic) {
return element.nodeName.toLowerCase() === 'html' ? null : element.parentNode;
}
for (parent = element.parentNode; parent && parent !== body; parent = parent.parentNode) {
positionStyle = _utils2['default'].css(parent, 'position');
if (positionStyle !== 'static') {
return parent;
}
}
return null;
}
exports['default'] = getOffsetParent;
module.exports = exports['default'];
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = isAncestorFixed;
var _utils = __webpack_require__(54);
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function isAncestorFixed(element) {
if (_utils2['default'].isWindow(element) || element.nodeType === 9) {
return false;
}
var doc = _utils2['default'].getDocument(element);
var body = doc.body;
var parent = null;
for (parent = element.parentNode; parent && parent !== body; parent = parent.parentNode) {
var positionStyle = _utils2['default'].css(parent, 'position');
if (positionStyle === 'fixed') {
return true;
}
}
return false;
}
module.exports = exports['default'];
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(54);
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function adjustForViewport(elFuturePos, elRegion, visibleRect, overflow) {
var pos = _utils2['default'].clone(elFuturePos);
var size = {
width: elRegion.width,
height: elRegion.height
};
if (overflow.adjustX && pos.left < visibleRect.left) {
pos.left = visibleRect.left;
}
// Left edge inside and right edge outside viewport, try to resize it.
if (overflow.resizeWidth && pos.left >= visibleRect.left && pos.left + size.width > visibleRect.right) {
size.width -= pos.left + size.width - visibleRect.right;
}
// Right edge outside viewport, try to move it.
if (overflow.adjustX && pos.left + size.width > visibleRect.right) {
// 保证左边界和可视区域左边界对齐
pos.left = Math.max(visibleRect.right - size.width, visibleRect.left);
}
// Top edge outside viewport, try to move it.
if (overflow.adjustY && pos.top < visibleRect.top) {
pos.top = visibleRect.top;
}
// Top edge inside and bottom edge outside viewport, try to resize it.
if (overflow.resizeHeight && pos.top >= visibleRect.top && pos.top + size.height > visibleRect.bottom) {
size.height -= pos.top + size.height - visibleRect.bottom;
}
// Bottom edge outside viewport, try to move it.
if (overflow.adjustY && pos.top + size.height > visibleRect.bottom) {
// 保证上边界和可视区域上边界对齐
pos.top = Math.max(visibleRect.bottom - size.height, visibleRect.top);
}
return _utils2['default'].mix(pos, size);
}
exports['default'] = adjustForViewport;
module.exports = exports['default'];
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(54);
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function getRegion(node) {
var offset = void 0;
var w = void 0;
var h = void 0;
if (!_utils2['default'].isWindow(node) && node.nodeType !== 9) {
offset = _utils2['default'].offset(node);
w = _utils2['default'].outerWidth(node);
h = _utils2['default'].outerHeight(node);
} else {
var win = _utils2['default'].getWindow(node);
offset = {
left: _utils2['default'].getWindowScrollLeft(win),
top: _utils2['default'].getWindowScrollTop(win)
};
w = _utils2['default'].viewportWidth(win);
h = _utils2['default'].viewportHeight(win);
}
offset.width = w;
offset.height = h;
return offset;
}
exports['default'] = getRegion;
module.exports = exports['default'];
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getAlignOffset = __webpack_require__(62);
var _getAlignOffset2 = _interopRequireDefault(_getAlignOffset);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function getElFuturePos(elRegion, refNodeRegion, points, offset, targetOffset) {
var p1 = (0, _getAlignOffset2['default'])(refNodeRegion, points[1]);
var p2 = (0, _getAlignOffset2['default'])(elRegion, points[0]);
var diff = [p2.left - p1.left, p2.top - p1.top];
return {
left: elRegion.left - diff[0] + offset[0] - targetOffset[0],
top: elRegion.top - diff[1] + offset[1] - targetOffset[1]
};
}
exports['default'] = getElFuturePos;
module.exports = exports['default'];
/***/ }),
/* 62 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* 获取 node 上的 align 对齐点 相对于页面的坐标
*/
function getAlignOffset(region, align) {
var V = align.charAt(0);
var H = align.charAt(1);
var w = region.width;
var h = region.height;
var x = region.left;
var y = region.top;
if (V === 'c') {
y += h / 2;
} else if (V === 'b') {
y += h;
}
if (H === 'c') {
x += w / 2;
} else if (H === 'r') {
x += w;
}
return {
left: x,
top: y
};
}
exports['default'] = getAlignOffset;
module.exports = exports['default'];
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _utils = __webpack_require__(54);
var _utils2 = _interopRequireDefault(_utils);
var _align = __webpack_require__(53);
var _align2 = _interopRequireDefault(_align);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* `tgtPoint`: { pageX, pageY } or { clientX, clientY }.
* If client position provided, will internal convert to page position.
*/
function alignPoint(el, tgtPoint, align) {
var pageX = void 0;
var pageY = void 0;
var doc = _utils2['default'].getDocument(el);
var win = doc.defaultView || doc.parentWindow;
var scrollX = _utils2['default'].getWindowScrollLeft(win);
var scrollY = _utils2['default'].getWindowScrollTop(win);
var viewportWidth = _utils2['default'].viewportWidth(win);
var viewportHeight = _utils2['default'].viewportHeight(win);
if ('pageX' in tgtPoint) {
pageX = tgtPoint.pageX;
} else {
pageX = scrollX + tgtPoint.clientX;
}
if ('pageY' in tgtPoint) {
pageY = tgtPoint.pageY;
} else {
pageY = scrollY + tgtPoint.clientY;
}
var tgtRegion = {
left: pageX,
top: pageY,
width: 0,
height: 0
};
var pointInView = pageX >= 0 && pageX <= scrollX + viewportWidth && pageY >= 0 && pageY <= scrollY + viewportHeight;
// Provide default target point
var points = [align.points[0], 'cc'];
return (0, _align2['default'])(el, tgtRegion, _extends({}, align, { points: points }), pointInView);
}
exports['default'] = alignPoint;
module.exports = exports['default'];
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _Transition = __webpack_require__(12);
var _Transition2 = _interopRequireDefault(_Transition);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
/**
* Show the component; triggers the fade in or fade out animation
*/
"in": _propTypes2["default"].bool,
/**
* Unmount the component (remove it from the DOM) when it is faded out
*/
unmountOnExit: _propTypes2["default"].bool,
/**
* Run the fade in animation when the component mounts, if it is initially
* shown
*/
transitionAppear: _propTypes2["default"].bool,
/**
* Duration of the fade animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
timeout: _propTypes2["default"].number,
/**
* Callback fired before the component fades in
*/
onEnter: _propTypes2["default"].func,
/**
* Callback fired after the component starts to fade in
*/
onEntering: _propTypes2["default"].func,
/**
* Callback fired after the has component faded in
*/
onEntered: _propTypes2["default"].func,
/**
* Callback fired before the component fades out
*/
onExit: _propTypes2["default"].func,
/**
* Callback fired after the component starts to fade out
*/
onExiting: _propTypes2["default"].func,
/**
* Callback fired after the component has faded out
*/
onExited: _propTypes2["default"].func
};
var defaultProps = {
"in": false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false
};
var Fade = function (_React$Component) {
_inherits(Fade, _React$Component);
function Fade() {
_classCallCheck(this, Fade);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Fade.prototype.render = function render() {
return _react2["default"].createElement(_Transition2["default"], _extends({}, this.props, {
className: (0, _classnames2["default"])(this.props.className, 'fade'),
enteredClassName: 'in',
enteringClassName: 'in'
}));
};
return Fade;
}(_react2["default"].Component);
Fade.propTypes = propTypes;
Fade.defaultProps = defaultProps;
exports["default"] = Fade;
module.exports = exports['default'];
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Message = __webpack_require__(66);
var _Message2 = _interopRequireDefault(_Message);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Message2["default"];
module.exports = exports['default'];
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _beeNotification = __webpack_require__(67);
var _beeNotification2 = _interopRequireDefault(_beeNotification);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _warning = __webpack_require__(32);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var defaultDuration = 1.5;
var newDuration = void 0;
var defaultTop = 24;
var defaultBottom = 48;
var bottom = 90;
var padding = 30;
var width = 240;
var messageInstance = void 0;
var key = 1;
var clsPrefix = 'u-message';
var noop = function noop() {};
var notificationStyle_copy = {};
var messageStyle_copy = {};
var positionType = ['topRight', 'bottomRight', 'top', 'bottom', 'topLeft', 'bottomLeft', ''];
var defaultStyle = {};
var positionObj = {
"top": {
messageStyle: {},
notificationStyle: {
top: defaultTop,
left: '50%',
transform: 'translateX( -50%)'
},
transitionName: 'top'
},
"bottom": {
messageStyle: {},
notificationStyle: {
bottom: defaultBottom,
left: '50%',
transform: 'translateX( -50%)'
},
transitionName: 'bottom'
},
"topRight": {
messageStyle: {
width: width
},
notificationStyle: {
top: padding,
right: padding,
width: width
},
transitionName: 'right'
},
"bottomRight": {
messageStyle: {
width: width
},
notificationStyle: {
bottom: bottom,
right: padding,
width: width
},
transitionName: 'right'
},
"topLeft": {
messageStyle: {
width: width
},
notificationStyle: {
top: padding,
left: padding,
width: width
},
transitionName: 'left'
},
"bottomLeft": {
messageStyle: {
width: width
},
notificationStyle: {
bottom: bottom,
left: padding,
width: width
},
transitionName: 'left'
}
};
function getMessageInstance() {
var position = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'top';
var callback = arguments[1];
var keyboard = arguments[2];
var onEscapeKeyUp = arguments[3];
if (messageInstance) {
callback(messageInstance);
return;
}
switch (position) {
case 'top':
notificationStyle_copy.top = defaultTop;
break;
case 'bottom':
notificationStyle_copy.bottom = defaultBottom;
break;
case 'bottomRight':
notificationStyle_copy.bottom = bottom;
break;
case 'bottomLeft':
notificationStyle_copy.bottom = bottom;
break;
default:
break;
}
if (position !== 'top' && position !== 'bottom') {
messageStyle_copy.width = width;
}
var style = JSON.stringify(notificationStyle_copy) == "{}" ? positionObj[position].notificationStyle : notificationStyle_copy;
var instanceObj = {
clsPrefix: clsPrefix,
transitionName: clsPrefix + '-' + positionObj[position].transitionName,
style: _extends({}, style, defaultStyle), // 覆盖原来的样式
position: position
};
if (typeof keyboard === 'boolean') {
instanceObj.keyboard = keyboard;
}
if (typeof onEscapeKeyUp === 'function') {
instanceObj.onEscapeKeyUp = onEscapeKeyUp;
}
_beeNotification2["default"].newInstance(instanceObj, function (instance) {
messageInstance = instance;
callback(instance);
});
}
function notice(content, duration_arg, type, onClose, position, style, keyboard, onEscapeKeyUp, showIcon, icon, props) {
if (positionType.findIndex(function (item) {
return item === position;
}) < 0) {
(0, _warning2["default"])(false, 'Failed prop type: Invalid prop `position` supplied to `Message`, expected one of ["top","bottom","topRight","topLeft","bottomRight","bottomLeft"].');
return;
}
var duration = duration_arg !== undefined ? duration_arg : defaultDuration;
notificationStyle_copy = _extends({}, positionObj[position].notificationStyle);
messageStyle_copy = _extends({}, positionObj[position].messageStyle);
var iconType = {
info: 'uf uf-i-c-2',
success: 'uf uf-correct',
danger: 'uf uf-exc-c',
warning: 'uf uf-exc-t',
light: 'uf uf-notification',
dark: 'uf uf-notification',
news: 'uf uf-bell',
infolight: 'uf uf-i-c-2',
successlight: 'uf uf-correct',
dangerlight: 'uf uf-exc-c',
warninglight: 'uf uf-exc-t'
}[type];
var positionStyle = JSON.stringify(messageStyle_copy) == "{}" ? positionObj[position].messageStyle : messageStyle_copy;
defaultStyle = _extends({}, positionStyle, style);
getMessageInstance(position, function (instance) {
instance.notice(_extends({}, props, {
key: key,
duration: duration,
color: type,
style: _extends({}, positionStyle, style),
content: _react2["default"].createElement(
'div',
null,
showIcon ? _react2["default"].createElement(
'div',
{ className: clsPrefix + '-notice-description-icon' },
icon ? _react2["default"].createElement('i', { className: (0, _classnames2["default"])('' + icon) }) : _react2["default"].createElement('i', { className: (0, _classnames2["default"])(iconType) })
) : null,
_react2["default"].createElement(
'div',
{ className: clsPrefix + '-notice-description-content' },
content
)
),
onClose: onClose
}));
}, keyboard, onEscapeKeyUp);
return function () {
var target = key++;
return function () {
if (messageInstance) {
messageInstance.removeNotice(target);
}
};
}();
}
exports["default"] = {
create: function create(obj) {
if (newDuration) {
//如果在config方法里设置了duration
obj.duration = newDuration;
}
var content = obj.content || '';
var duration = typeof obj.duration == 'undefined' ? defaultDuration : obj.duration;
var color = obj.color || 'light';
var onClose = obj.onClose || noop;
var position = obj.position || "top";
var style = obj.style || {};
var showIcon = obj.hasOwnProperty('showIcon') ? obj.showIcon : true;
var icon = obj.hasOwnProperty('icon') ? obj.icon : false;
return notice(content, duration, color, onClose, position, style, obj.keyboard, obj.onEscapeKeyUp, showIcon, icon, obj);
},
config: function config(options) {
if (options.top !== undefined) {
defaultTop = options.top;
}
if (options.duration !== undefined) {
defaultDuration = options.duration;
newDuration = defaultDuration;
}
if (options.clsPrefix !== undefined) {
clsPrefix = options.clsPrefix;
}
if (options.defaultBottom !== undefined) {
defaultBottom = options.defaultBottom;
}
if (options.bottom !== undefined) {
bottom = options.bottom;
}
if (options.width !== undefined) {
width = options.width;
}
},
destroy: function destroy() {
if (messageInstance) {
messageInstance.destroy();
messageInstance = null;
defaultDuration = 1.5;
newDuration = undefined;
defaultTop = 24;
defaultBottom = 48;
bottom = 90;
padding = 30;
width = 240;
notificationStyle_copy = null;
messageStyle_copy = null;
defaultStyle = null;
}
}
};
module.exports = exports['default'];
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Notification = __webpack_require__(68);
var _Notification2 = _interopRequireDefault(_Notification);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Notification2["default"];
module.exports = exports['default'];
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _beeAnimate = __webpack_require__(69);
var _beeAnimate2 = _interopRequireDefault(_beeAnimate);
var _createChainedFunction = __webpack_require__(37);
var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction);
var _ownerDocument = __webpack_require__(74);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
var _addEventListener = __webpack_require__(76);
var _addEventListener2 = _interopRequireDefault(_addEventListener);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _Notice = __webpack_require__(78);
var _Notice2 = _interopRequireDefault(_Notice);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var seed = 0;
var now = Date.now();
function getUuid() {
return 'uNotification_' + now + '_' + seed++;
}
var propTypes = {
show: _propTypes2["default"].bool,
clsPrefix: _propTypes2["default"].string,
style: _propTypes2["default"].object,
position: _propTypes2["default"].oneOf(['topRight', 'bottomRight', 'top', 'bottom', 'topLeft', 'bottomLeft', '']),
transitionName: _propTypes2["default"].string,
keyboard: _propTypes2["default"].bool, // 按esc键是否关闭notice
onEscapeKeyUp: _propTypes2["default"].func, // 设置esc键特殊钩子函数
animation: _propTypes2["default"].oneOfType([_propTypes2["default"].string, _propTypes2["default"].object])
};
var defaultProps = {
clsPrefix: 'u-notification',
animation: 'fade',
keyboard: true,
position: 'topRight'
};
var Notification = function (_Component) {
_inherits(Notification, _Component);
function Notification(props) {
_classCallCheck(this, Notification);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.handleDocumentKeyUp = function (e) {
if (_this.props.keyboard && e.keyCode === 27 && _this.state.notices.length) {
_this.setState(function (previousState) {
previousState.notices.shift();
return {
notices: previousState.notices
};
});
if (_this.props.onEscapeKeyUp) {
_this.props.onEscapeKeyUp(e);
}
}
};
_this.state = {
notices: []
};
_this.add = _this.add.bind(_this);
_this.remove = _this.remove.bind(_this);
return _this;
}
Notification.prototype.componentDidMount = function componentDidMount() {
// 给document绑定keyup事件
var doc = (0, _ownerDocument2["default"])(this);
this._onDocumentKeyupListener = (0, _addEventListener2["default"])(doc, 'keyup', this.handleDocumentKeyUp);
};
Notification.prototype.componentWillUnmount = function componentWillUnmount() {
this._onDocumentKeyupListener.remove();
};
Notification.prototype.getTransitionName = function getTransitionName() {
var props = this.props;
var transitionName = props.transitionName;
if (!transitionName && props.animation) {
transitionName = props.clsPrefix + '-' + props.animation;
}
return transitionName;
};
Notification.prototype.add = function add(notice) {
var key = notice.key = notice.key || getUuid();
this.setState(function (previousState) {
var notices = previousState.notices;
if (!notices.filter(function (v) {
return v.key === key;
}).length) {
return {
notices: notices.concat(notice)
};
}
});
};
Notification.prototype.remove = function remove(key) {
this.setState(function (previousState) {
return {
notices: previousState.notices.filter(function (notice) {
return notice.key !== key;
})
};
});
};
/**
* 处理绑定在document上的keyup事件
*/
Notification.prototype.render = function render() {
var _this2 = this,
_classes;
var _props = this.props,
clsPrefix = _props.clsPrefix,
className = _props.className,
position = _props.position,
style = _props.style;
var noticeNodes = this.state.notices.map(function (notice) {
var onClose = (0, _createChainedFunction2["default"])(_this2.remove.bind(_this2, notice.key), notice.onClose);
return _react2["default"].createElement(
_Notice2["default"],
_extends({
clsPrefix: clsPrefix
}, notice, {
onClose: onClose
}),
notice.content
);
});
var classes = (_classes = {}, _defineProperty(_classes, clsPrefix, 1), _defineProperty(_classes, className, !!className), _classes);
if (position) {
classes[clsPrefix + '-' + position] = !!position;
}
return _react2["default"].createElement(
'div',
{ className: (0, _classnames2["default"])(className, classes), style: style },
_react2["default"].createElement(
_beeAnimate2["default"],
{ transitionName: this.getTransitionName() },
noticeNodes
)
);
};
return Notification;
}(_react.Component);
;
Notification.propTypes = propTypes;
Notification.defaultProps = defaultProps;
Notification.newInstance = function newNotificationInstance(properties, callback) {
if (typeof callback !== 'function') {
console.error('You must introduce callback as the second parameter of Notification.newInstance().');
return;
}
var props = properties || {};
var container = props.container || document.body;
if (typeof container == 'function') {
container = container();
}
var div = document.createElement('div');
container.appendChild(div);
var called = false;
function ref(notification) {
if (called) {
return;
}
called = true;
callback({
notice: function notice(noticeProps) {
notification.add(noticeProps);
},
removeNotice: function removeNotice(key) {
notification.remove(key);
},
component: notification,
destroy: function destroy() {
_reactDom2["default"].unmountComponentAtNode(div);
container.removeChild(div);
}
});
}
_reactDom2["default"].render(_react2["default"].createElement(Notification, _extends({}, props, { ref: ref })), div);
};
exports["default"] = Notification;
module.exports = exports['default'];
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Animate = __webpack_require__(70);
var _Animate2 = _interopRequireDefault(_Animate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Animate2["default"];
module.exports = exports['default'];
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _ChildrenUtils = __webpack_require__(71);
var _AnimateChild = __webpack_require__(72);
var _AnimateChild2 = _interopRequireDefault(_AnimateChild);
var _util = __webpack_require__(73);
var _util2 = _interopRequireDefault(_util);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var defaultKey = 'u_animate_' + Date.now();
function getChildrenFromProps(props) {
var children = props.children;
if (_react2["default"].isValidElement(children)) {
if (!children.key) {
return _react2["default"].cloneElement(children, {
key: defaultKey
});
}
}
return children;
}
function noop() {}
var propTypes = {
component: _propTypes2["default"].any,
animation: _propTypes2["default"].object,
transitionName: _propTypes2["default"].oneOfType([_propTypes2["default"].string, _propTypes2["default"].object]),
transitionEnter: _propTypes2["default"].bool,
transitionAppear: _propTypes2["default"].bool,
exclusive: _propTypes2["default"].bool,
transitionLeave: _propTypes2["default"].bool,
onEnd: _propTypes2["default"].func,
onEnter: _propTypes2["default"].func,
onLeave: _propTypes2["default"].func,
onAppear: _propTypes2["default"].func,
showProp: _propTypes2["default"].string
};
var defaultProps = {
animation: {},
component: 'span',
transitionEnter: true,
transitionLeave: true,
transitionAppear: false,
onEnd: noop,
onEnter: noop,
onLeave: noop,
onAppear: noop
};
var Animate = function (_Component) {
_inherits(Animate, _Component);
function Animate(props) {
_classCallCheck(this, Animate);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.currentlyAnimatingKeys = {};
_this.keysToEnter = [];
_this.keysToLeave = [];
_this.state = {
children: (0, _ChildrenUtils.toArrayChildren)(getChildrenFromProps(_this.props))
};
_this.performEnter = _this.performEnter.bind(_this);
_this.performAppear = _this.performAppear.bind(_this);
_this.handleDoneAdding = _this.handleDoneAdding.bind(_this);
_this.performLeave = _this.performLeave.bind(_this);
_this.performLeave = _this.performLeave.bind(_this);
_this.handleDoneLeaving = _this.handleDoneLeaving.bind(_this);
_this.isValidChildByKey = _this.isValidChildByKey.bind(_this);
_this.stop = _this.stop.bind(_this);
return _this;
}
Animate.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
this.mounted = true;
var showProp = this.props.showProp;
var children = this.state.children;
if (showProp) {
children = children.filter(function (child) {
return !!child.props[showProp];
});
}
children.forEach(function (child) {
if (child) {
_this2.performAppear(child.key);
}
});
};
Animate.prototype.componentWillUnmount = function componentWillUnmount() {
this.mounted = false;
};
Animate.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var _this3 = this;
this.nextProps = nextProps;
var nextChildren = (0, _ChildrenUtils.toArrayChildren)(getChildrenFromProps(nextProps));
var props = this.props;
// exclusive needs immediate response
if (props.exclusive) {
Object.keys(this.currentlyAnimatingKeys).forEach(function (key) {
_this3.stop(key);
});
}
var showProp = props.showProp;
var currentlyAnimatingKeys = this.currentlyAnimatingKeys;
// last props children if exclusive
var currentChildren = props.exclusive ? (0, _ChildrenUtils.toArrayChildren)(getChildrenFromProps(props)) : this.state.children;
// in case destroy in showProp mode
var newChildren = [];
if (showProp) {
currentChildren.forEach(function (currentChild) {
var nextChild = currentChild && (0, _ChildrenUtils.findChildInChildrenByKey)(nextChildren, currentChild.key);
var newChild = void 0;
if ((!nextChild || !nextChild.props[showProp]) && currentChild.props[showProp]) {
newChild = _react2["default"].cloneElement(nextChild || currentChild, _defineProperty({}, showProp, true));
} else {
newChild = nextChild;
}
if (newChild) {
newChildren.push(newChild);
}
});
nextChildren.forEach(function (nextChild) {
if (!nextChild || !(0, _ChildrenUtils.findChildInChildrenByKey)(currentChildren, nextChild.key)) {
newChildren.push(nextChild);
}
});
} else {
newChildren = (0, _ChildrenUtils.mergeChildren)(currentChildren, nextChildren);
}
// need render to avoid update
this.setState({
children: newChildren
});
nextChildren.forEach(function (child) {
var key = child && child.key;
if (child && currentlyAnimatingKeys[key]) {
return;
}
var hasPrev = child && (0, _ChildrenUtils.findChildInChildrenByKey)(currentChildren, key);
if (showProp) {
var showInNext = child.props[showProp];
if (hasPrev) {
var showInNow = (0, _ChildrenUtils.findShownChildInChildrenByKey)(currentChildren, key, showProp);
if (!showInNow && showInNext) {
_this3.keysToEnter.push(key);
}
} else if (showInNext) {
_this3.keysToEnter.push(key);
}
} else if (!hasPrev) {
_this3.keysToEnter.push(key);
}
});
currentChildren.forEach(function (child) {
var key = child && child.key;
if (child && currentlyAnimatingKeys[key]) {
return;
}
var hasNext = child && (0, _ChildrenUtils.findChildInChildrenByKey)(nextChildren, key);
if (showProp) {
var showInNow = child.props[showProp];
if (hasNext) {
var showInNext = (0, _ChildrenUtils.findShownChildInChildrenByKey)(nextChildren, key, showProp);
if (!showInNext && showInNow) {
_this3.keysToLeave.push(key);
}
} else if (showInNow) {
_this3.keysToLeave.push(key);
}
} else if (!hasNext) {
_this3.keysToLeave.push(key);
}
});
};
Animate.prototype.componentDidUpdate = function componentDidUpdate() {
var keysToEnter = this.keysToEnter;
this.keysToEnter = [];
keysToEnter.forEach(this.performEnter);
var keysToLeave = this.keysToLeave;
this.keysToLeave = [];
keysToLeave.forEach(this.performLeave);
};
Animate.prototype.performEnter = function performEnter(key) {
// may already remove by exclusive
if (this.refs[key]) {
this.currentlyAnimatingKeys[key] = true;
this.refs[key].componentWillEnter(this.handleDoneAdding.bind(this, key, 'enter'));
}
};
Animate.prototype.performAppear = function performAppear(key) {
if (this.refs[key]) {
this.currentlyAnimatingKeys[key] = true;
this.refs[key].componentWillAppear(this.handleDoneAdding.bind(this, key, 'appear'));
}
};
Animate.prototype.handleDoneAdding = function handleDoneAdding(key, type) {
var props = this.props;
delete this.currentlyAnimatingKeys[key];
// if update on exclusive mode, skip check
if (props.exclusive && props !== this.nextProps) {
return;
}
var currentChildren = (0, _ChildrenUtils.toArrayChildren)(getChildrenFromProps(props));
if (!this.isValidChildByKey(currentChildren, key)) {
// exclusive will not need this
this.performLeave(key);
} else {
if (type === 'appear') {
if (_util2["default"].allowAppearCallback(props)) {
props.onAppear(key);
props.onEnd(key, true);
}
} else {
if (_util2["default"].allowEnterCallback(props)) {
props.onEnter(key);
props.onEnd(key, true);
}
}
}
};
Animate.prototype.performLeave = function performLeave(key) {
// may already remove by exclusive
if (this.refs[key]) {
this.currentlyAnimatingKeys[key] = true;
this.refs[key].componentWillLeave(this.handleDoneLeaving.bind(this, key));
}
};
Animate.prototype.handleDoneLeaving = function handleDoneLeaving(key) {
var props = this.props;
delete this.currentlyAnimatingKeys[key];
// if update on exclusive mode, skip check
if (props.exclusive && props !== this.nextProps) {
return;
}
var currentChildren = (0, _ChildrenUtils.toArrayChildren)(getChildrenFromProps(props));
// in case state change is too fast
if (this.isValidChildByKey(currentChildren, key)) {
this.performEnter(key);
} else {
var end = function end() {
if (_util2["default"].allowLeaveCallback(props)) {
props.onLeave(key);
props.onEnd(key, false);
}
};
/* eslint react/no-is-mounted:0 */
if (this.mounted && !(0, _ChildrenUtils.isSameChildren)(this.state.children, currentChildren, props.showProp)) {
this.setState({
children: currentChildren
}, end);
} else {
end();
}
}
};
Animate.prototype.isValidChildByKey = function isValidChildByKey(currentChildren, key) {
var showProp = this.props.showProp;
if (showProp) {
return (0, _ChildrenUtils.findShownChildInChildrenByKey)(currentChildren, key, showProp);
}
return (0, _ChildrenUtils.findChildInChildrenByKey)(currentChildren, key);
};
Animate.prototype.stop = function stop(key) {
delete this.currentlyAnimatingKeys[key];
var component = this.refs[key];
if (component) {
component.stop();
}
};
Animate.prototype.render = function render() {
var props = this.props;
this.nextProps = props;
var stateChildren = this.state.children;
var children = null;
if (stateChildren) {
children = stateChildren.map(function (child) {
if (child === null || child === undefined) {
return child;
}
if (!child.key) {
throw new Error('must set key for <rc-animate> children');
}
return _react2["default"].createElement(
_AnimateChild2["default"],
{
key: child.key,
ref: child.key,
animation: props.animation,
transitionName: props.transitionName,
transitionEnter: props.transitionEnter,
transitionAppear: props.transitionAppear,
transitionLeave: props.transitionLeave
},
child
);
});
}
var Component = props.component;
if (Component) {
var passedProps = props;
if (typeof Component === 'string') {
passedProps = {
className: props.className,
style: props.style
};
}
return _react2["default"].createElement(
Component,
passedProps,
children
);
}
return children[0] || null;
};
return Animate;
}(_react.Component);
;
Animate.defaultProps = defaultProps;
Animate.propTypes = Animate.propTypes;
exports["default"] = Animate;
module.exports = exports['default'];
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.toArrayChildren = toArrayChildren;
exports.findChildInChildrenByKey = findChildInChildrenByKey;
exports.findShownChildInChildrenByKey = findShownChildInChildrenByKey;
exports.findHiddenChildInChildrenByKey = findHiddenChildInChildrenByKey;
exports.isSameChildren = isSameChildren;
exports.mergeChildren = mergeChildren;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function toArrayChildren(children) {
var ret = [];
_react2["default"].Children.forEach(children, function (child) {
ret.push(child);
});
return ret;
}
function findChildInChildrenByKey(children, key) {
var ret = null;
if (children) {
children.forEach(function (child) {
if (ret) {
return;
}
if (child && child.key === key) {
ret = child;
}
});
}
return ret;
}
function findShownChildInChildrenByKey(children, key, showProp) {
var ret = null;
if (children) {
children.forEach(function (child) {
if (child && child.key === key && child.props[showProp]) {
if (ret) {
throw new Error('two child with same key for <rc-animate> children');
}
ret = child;
}
});
}
return ret;
}
function findHiddenChildInChildrenByKey(children, key, showProp) {
var found = 0;
if (children) {
children.forEach(function (child) {
if (found) {
return;
}
found = child && child.key === key && !child.props[showProp];
});
}
return found;
}
function isSameChildren(c1, c2, showProp) {
var same = c1.length === c2.length;
if (same) {
c1.forEach(function (child, index) {
var child2 = c2[index];
if (child && child2) {
if (child && !child2 || !child && child2) {
same = false;
} else if (child.key !== child2.key) {
same = false;
} else if (showProp && child.props[showProp] !== child2.props[showProp]) {
same = false;
}
}
});
}
return same;
}
function mergeChildren(prev, next) {
var ret = [];
// For each key of `next`, the list of keys to insert before that key in
// the combined list
var nextChildrenPending = {};
var pendingChildren = [];
prev.forEach(function (child) {
if (child && findChildInChildrenByKey(next, child.key)) {
if (pendingChildren.length) {
nextChildrenPending[child.key] = pendingChildren;
pendingChildren = [];
}
} else {
pendingChildren.push(child);
}
});
next.forEach(function (child) {
if (child && nextChildrenPending.hasOwnProperty(child.key)) {
ret = ret.concat(nextChildrenPending[child.key]);
}
ret.push(child);
});
ret = ret.concat(pendingChildren);
return ret;
}
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _tinperBeeCore = __webpack_require__(27);
var _util = __webpack_require__(73);
var _util2 = _interopRequireDefault(_util);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var transitionMap = {
enter: 'transitionEnter',
appear: 'transitionAppear',
leave: 'transitionLeave'
};
var propTypes = {
children: _propTypes2["default"].any
};
var AnimateChild = function (_Component) {
_inherits(AnimateChild, _Component);
function AnimateChild(props) {
_classCallCheck(this, AnimateChild);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.transition = _this.transition.bind(_this);
_this.stop = _this.stop.bind(_this);
return _this;
}
AnimateChild.prototype.componentWillUnmount = function componentWillUnmount() {
this.stop();
};
AnimateChild.prototype.componentWillEnter = function componentWillEnter(done) {
if (_util2["default"].isEnterSupported(this.props)) {
this.transition('enter', done);
} else {
done();
}
};
AnimateChild.prototype.componentWillAppear = function componentWillAppear(done) {
if (_util2["default"].isAppearSupported(this.props)) {
this.transition('appear', done);
} else {
done();
}
};
AnimateChild.prototype.componentWillLeave = function componentWillLeave(done) {
if (_util2["default"].isLeaveSupported(this.props)) {
this.transition('leave', done);
} else {
// always sync, do not interupt with react component life cycle
// update hidden -> animate hidden ->
// didUpdate -> animate leave -> unmount (if animate is none)
done();
}
};
AnimateChild.prototype.transition = function transition(animationType, finishCallback) {
var _this2 = this;
var node = _reactDom2["default"].findDOMNode(this);
var props = this.props;
var transitionName = props.transitionName;
var nameIsObj = (typeof transitionName === 'undefined' ? 'undefined' : _typeof(transitionName)) === 'object';
this.stop();
var end = function end() {
_this2.stopper = null;
finishCallback();
};
if ((_tinperBeeCore.cssAnimation.isCssAnimationSupported || !props.animation[animationType]) && transitionName && props[transitionMap[animationType]]) {
var name = nameIsObj ? transitionName[animationType] : transitionName + '-' + animationType;
var activeName = name + '-active';
if (nameIsObj && transitionName[animationType + 'Active']) {
activeName = transitionName[animationType + 'Active'];
}
this.stopper = (0, _tinperBeeCore.cssAnimation)(node, {
name: name,
active: activeName
}, end);
} else {
this.stopper = props.animation[animationType](node, end);
}
};
AnimateChild.prototype.stop = function stop() {
var stopper = this.stopper;
if (stopper) {
this.stopper = null;
stopper.stop();
}
};
AnimateChild.prototype.render = function render() {
return this.props.children;
};
return AnimateChild;
}(_react.Component);
;
AnimateChild.propTypes = propTypes;
exports["default"] = AnimateChild;
module.exports = exports['default'];
/***/ }),
/* 73 */
/***/ (function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var util = {
isAppearSupported: function isAppearSupported(props) {
return props.transitionName && props.transitionAppear || props.animation.appear;
},
isEnterSupported: function isEnterSupported(props) {
return props.transitionName && props.transitionEnter || props.animation.enter;
},
isLeaveSupported: function isLeaveSupported(props) {
return props.transitionName && props.transitionLeave || props.animation.leave;
},
allowAppearCallback: function allowAppearCallback(props) {
return props.transitionAppear || props.animation.appear;
},
allowEnterCallback: function allowEnterCallback(props) {
return props.transitionEnter || props.animation.enter;
},
allowLeaveCallback: function allowLeaveCallback(props) {
return props.transitionLeave || props.animation.leave;
}
};
exports["default"] = util;
module.exports = exports["default"];
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = function (componentOrElement) {
return (0, _ownerDocument2["default"])(_reactDom2["default"].findDOMNode(componentOrElement));
};
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _ownerDocument = __webpack_require__(75);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
module.exports = exports['default'];
/***/ }),
/* 75 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = ownerDocument;
function ownerDocument(node) {
return node && node.ownerDocument || document;
}
module.exports = exports["default"];
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = function (node, event, handler, capture) {
(0, _on2["default"])(node, event, handler, capture);
return {
remove: function remove() {
(0, _off2["default"])(node, event, handler, capture);
}
};
};
var _on = __webpack_require__(16);
var _on2 = _interopRequireDefault(_on);
var _off = __webpack_require__(77);
var _off2 = _interopRequireDefault(_off);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
module.exports = exports['default'];
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = void 0;
var _inDOM = _interopRequireDefault(__webpack_require__(15));
var off = function off() {};
if (_inDOM.default) {
off = function () {
if (document.addEventListener) return function (node, eventName, handler, capture) {
return node.removeEventListener(eventName, handler, capture || false);
};else if (document.attachEvent) return function (node, eventName, handler) {
return node.detachEvent('on' + eventName, handler);
};
}();
}
var _default = off;
exports.default = _default;
module.exports = exports["default"];
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _beeIcon = __webpack_require__(79);
var _beeIcon2 = _interopRequireDefault(_beeIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
duration: _propTypes2["default"].number,
onClose: _propTypes2["default"].func,
children: _propTypes2["default"].any,
color: _propTypes2["default"].oneOf(['info', 'success', 'danger', 'warning', 'light', 'dark', 'news', 'infolight', 'successlight', 'dangerlight', 'warninglight']),
title: _propTypes2["default"].any
};
function noop() {}
var defaultProps = {
onEnd: noop,
onClose: noop,
duration: 4.5,
closable: true
};
var Notice = function (_React$Component) {
_inherits(Notice, _React$Component);
function Notice(props) {
_classCallCheck(this, Notice);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.clearCloseTimer = _this.clearCloseTimer.bind(_this);
_this.close = _this.close.bind(_this);
return _this;
}
Notice.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
if (this.props.duration) {
this.closeTimer = setTimeout(function () {
_this2.close();
}, this.props.duration * 1000);
}
};
Notice.prototype.componentWillUnmount = function componentWillUnmount() {
this.clearCloseTimer();
};
Notice.prototype.clearCloseTimer = function clearCloseTimer() {
if (this.closeTimer) {
clearTimeout(this.closeTimer);
this.closeTimer = null;
}
};
Notice.prototype.close = function close() {
this.clearCloseTimer();
this.props.onClose();
};
Notice.prototype.render = function render() {
var _classes;
var _props = this.props,
closable = _props.closable,
clsPrefix = _props.clsPrefix,
className = _props.className,
style = _props.style,
children = _props.children,
color = _props.color,
title = _props.title,
content = _props.content,
onEnd = _props.onEnd,
onClose = _props.onClose,
duration = _props.duration,
others = _objectWithoutProperties(_props, ['closable', 'clsPrefix', 'className', 'style', 'children', 'color', 'title', 'content', 'onEnd', 'onClose', 'duration']);
var componentClass = clsPrefix + '-notice';
var classes = (_classes = {}, _defineProperty(_classes, '' + componentClass, 1), _defineProperty(_classes, componentClass + '-closable', closable), _defineProperty(_classes, className, !!className), _classes);
if (color) {
classes[componentClass + '-' + color] = true;
}
return _react2["default"].createElement(
'div',
_extends({ className: (0, _classnames2["default"])(classes), style: style, onClick: this.close }, others),
_react2["default"].createElement(
'div',
{ className: componentClass + '-content' },
title && _react2["default"].createElement(
'div',
{ className: componentClass + '-title' },
title
),
_react2["default"].createElement(
'div',
{ className: componentClass + '-description' },
children
)
),
closable ? _react2["default"].createElement(
'a',
{ tabIndex: '0', onClick: this.close, className: componentClass + '-close' },
_react2["default"].createElement(
'span',
{ className: componentClass + '-close-x' },
_react2["default"].createElement(_beeIcon2["default"], { type: 'uf-close' })
)
) : null
);
};
return Notice;
}(_react2["default"].Component);
;
Notice.propTypes = propTypes;
Notice.defaultProps = defaultProps;
exports["default"] = Notice;
module.exports = exports['default'];
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Icon = __webpack_require__(80);
var _Icon2 = _interopRequireDefault(_Icon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Icon2["default"];
module.exports = exports['default'];
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
type: _propTypes2["default"].string
};
/**
* badge 默认显示内容1
*/
var defaultProps = {
clsPrefix: 'uf'
};
var Icon = function (_Component) {
_inherits(Icon, _Component);
function Icon(props) {
_classCallCheck(this, Icon);
return _possibleConstructorReturn(this, _Component.call(this, props));
}
Icon.prototype.render = function render() {
var _props = this.props,
type = _props.type,
className = _props.className,
clsPrefix = _props.clsPrefix,
others = _objectWithoutProperties(_props, ['type', 'className', 'clsPrefix']);
var clsObj = {};
var classNames = (0, _classnames2["default"])(clsPrefix, type);
return _react2["default"].createElement('i', _extends({}, others, { className: (0, _classnames2["default"])(classNames, className) }));
};
return Icon;
}(_react.Component);
Icon.defaultProps = defaultProps;
Icon.propTypes = propTypes;
exports["default"] = Icon;
module.exports = exports['default'];
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var deselectCurrent = __webpack_require__(82);
var clipboardToIE11Formatting = {
"text/plain": "Text",
"text/html": "Url",
"default": "Text"
}
var defaultMessage = "Copy to clipboard: #{key}, Enter";
function format(message) {
var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C";
return message.replace(/#{\s*key\s*}/g, copyKey);
}
function copy(text, options) {
var debug,
message,
reselectPrevious,
range,
selection,
mark,
success = false;
if (!options) {
options = {};
}
debug = options.debug || false;
try {
reselectPrevious = deselectCurrent();
range = document.createRange();
selection = document.getSelection();
mark = document.createElement("span");
mark.textContent = text;
// reset user styles for span element
mark.style.all = "unset";
// prevents scrolling to the end of the page
mark.style.position = "fixed";
mark.style.top = 0;
mark.style.clip = "rect(0, 0, 0, 0)";
// used to preserve spaces and line breaks
mark.style.whiteSpace = "pre";
// do not inherit user-select (it may be `none`)
mark.style.webkitUserSelect = "text";
mark.style.MozUserSelect = "text";
mark.style.msUserSelect = "text";
mark.style.userSelect = "text";
mark.addEventListener("copy", function(e) {
e.stopPropagation();
if (options.format) {
e.preventDefault();
if (typeof e.clipboardData === "undefined") { // IE 11
debug && console.warn("unable to use e.clipboardData");
debug && console.warn("trying IE specific stuff");
window.clipboardData.clearData();
var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]
window.clipboardData.setData(format, text);
} else { // all other browsers
e.clipboardData.clearData();
e.clipboardData.setData(options.format, text);
}
}
if (options.onCopy) {
e.preventDefault();
options.onCopy(e.clipboardData);
}
});
document.body.appendChild(mark);
range.selectNodeContents(mark);
selection.addRange(range);
var successful = document.execCommand("copy");
if (!successful) {
throw new Error("copy command was unsuccessful");
}
success = true;
} catch (err) {
debug && console.error("unable to copy using execCommand: ", err);
debug && console.warn("trying IE specific stuff");
try {
window.clipboardData.setData(options.format || "text", text);
options.onCopy && options.onCopy(window.clipboardData);
success = true;
} catch (err) {
debug && console.error("unable to copy using clipboardData: ", err);
debug && console.error("falling back to prompt");
message = format("message" in options ? options.message : defaultMessage);
window.prompt(message, text);
}
} finally {
if (selection) {
if (typeof selection.removeRange == "function") {
selection.removeRange(range);
} else {
selection.removeAllRanges();
}
}
if (mark) {
document.body.removeChild(mark);
}
reselectPrevious();
}
return success;
}
module.exports = copy;
/***/ }),
/* 82 */
/***/ (function(module, exports) {
module.exports = function () {
var selection = document.getSelection();
if (!selection.rangeCount) {
return function () {};
}
var active = document.activeElement;
var ranges = [];
for (var i = 0; i < selection.rangeCount; i++) {
ranges.push(selection.getRangeAt(i));
}
switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML
case 'INPUT':
case 'TEXTAREA':
active.blur();
break;
default:
active = null;
break;
}
selection.removeAllRanges();
return function () {
selection.type === 'Caret' &&
selection.removeAllRanges();
if (!selection.rangeCount) {
ranges.forEach(function(range) {
selection.addRange(range);
});
}
active &&
active.focus();
};
};
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
//是否是手风琴效果
accordion: _propTypes2["default"].bool,
//激活的项
activeKey: _propTypes2["default"].any,
//默认的激活的项
defaultActiveKey: _propTypes2["default"].any,
//选中函数
onSelect: _propTypes2["default"].func,
role: _propTypes2["default"].string
};
var defaultProps = {
accordion: false,
clsPrefix: 'u-panel-group'
};
// TODO: Use uncontrollable.
var PanelGroup = function (_React$Component) {
_inherits(PanelGroup, _React$Component);
function PanelGroup(props, context) {
_classCallCheck(this, PanelGroup);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleSelect = _this.handleSelect.bind(_this);
_this.state = {
activeKey: props.defaultActiveKey
};
return _this;
}
PanelGroup.prototype.handleSelect = function handleSelect(key, e) {
e.preventDefault();
if (this.props.onSelect) {
this.props.onSelect(key, e);
}
if (this.state.activeKey === key) {
key = null;
}
this.setState({ activeKey: key });
};
PanelGroup.prototype.render = function render() {
var _this2 = this;
var _props = this.props,
accordion = _props.accordion,
propsActiveKey = _props.activeKey,
className = _props.className,
children = _props.children,
defaultActiveKey = _props.defaultActiveKey,
onSelect = _props.onSelect,
style = _props.style,
clsPrefix = _props.clsPrefix,
others = _objectWithoutProperties(_props, ['accordion', 'activeKey', 'className', 'children', 'defaultActiveKey', 'onSelect', 'style', 'clsPrefix']);
var activeKey = void 0;
if (accordion) {
activeKey = propsActiveKey != null ? propsActiveKey : this.state.activeKey;
others.role = others.role || 'tablist';
}
var classes = {};
classes['' + clsPrefix] = true;
return _react2["default"].createElement(
'div',
_extends({}, others, {
className: (0, _classnames2["default"])(className, classes)
}),
_react2["default"].Children.map(children, function (child) {
if (!_react2["default"].isValidElement(child)) {
return child;
}
var childProps = {
style: child.props.style
};
if (accordion) {
_extends(childProps, {
headerRole: 'tab',
panelRole: 'tabpanel',
collapsible: true,
expanded: child.props.eventKey === activeKey,
onSelect: (0, _tinperBeeCore.createChainedFunction)(_this2.handleSelect, child.props.onSelect)
});
}
return (0, _react.cloneElement)(child, childProps);
})
);
};
return PanelGroup;
}(_react2["default"].Component);
PanelGroup.propTypes = propTypes;
PanelGroup.defaultProps = defaultProps;
exports["default"] = PanelGroup;
module.exports = exports['default'];
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Drawer = __webpack_require__(85);
var _Drawer2 = _interopRequireDefault(_Drawer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Drawer2["default"];
module.exports = exports['default'];
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _common = __webpack_require__(86);
var _reactTransitionGroup = __webpack_require__(87);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
placement: _propTypes2["default"].oneOf(['left', 'right', 'top', 'bottom']),
hasHeader: _propTypes2["default"].bool,
show: _propTypes2["default"].bool,
title: _propTypes2["default"].string,
className: _propTypes2["default"].string,
showMask: _propTypes2["default"].bool,
maskClosable: _propTypes2["default"].bool,
zIndex: _propTypes2["default"].number,
showClose: _propTypes2["default"].bool,
width: _propTypes2["default"].oneOfType([_propTypes2["default"].string, _propTypes2["default"].number]),
height: _propTypes2["default"].oneOfType([_propTypes2["default"].string, _propTypes2["default"].number]),
destroyOnClose: _propTypes2["default"].bool,
container: _propTypes2["default"].string
};
var defaultProps = {
placement: 'left',
hasHeader: true,
show: false,
showMask: true,
maskClosable: true,
zIndex: 100000,
showClose: false,
width: 'auto',
height: 'auto',
destroyOnClose: false,
container: 'body'
};
var DrawerContext = _react2["default"].createContext(null);
var Drawer = function (_Component) {
_inherits(Drawer, _Component);
function Drawer(props) {
_classCallCheck(this, Drawer);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.state = {
showDrawer: true,
width: '0',
push: false
};
_this.drawer = null;
_this.parentDrawer = null;
(0, _common.bindAll)(_this, ['fMaskClick', 'fDrawerTransitionEnd', 'renderMask', 'renderClose', 'fCloseClick', 'renderBody', 'renderAll']);
return _this;
}
Drawer.prototype.componentDidUpdate = function componentDidUpdate(preProps) {
//在有父级抽屉时候,子级触发父级向外移动一段距离
if (preProps.show != this.props.show && this.parentDrawer) {
if (this.props.show) {
this.parentDrawer.push();
} else {
this.parentDrawer.pull();
}
}
};
Drawer.prototype.push = function push() {
this.setState({
push: true
});
};
Drawer.prototype.pull = function pull() {
this.setState({
push: false
});
};
Drawer.prototype.fMaskClick = function fMaskClick() {
var maskClosable = this.props.maskClosable;
if (maskClosable) {
var onClose = this.props.onClose;
onClose && onClose();
}
};
Drawer.prototype.fCloseClick = function fCloseClick() {
var onClose = this.props.onClose;
onClose && onClose();
};
Drawer.prototype.fDrawerTransitionEnd = function fDrawerTransitionEnd(e) {};
Drawer.prototype.renderMask = function renderMask() {
var _props = this.props,
show = _props.show,
showMask = _props.showMask,
fMaskClick = _props.fMaskClick;
//mask样式
var maskStyle = void 0;
if (show) {
maskStyle = {
opacity: 1,
width: '100%'
};
} else {
maskStyle = {
opacity: 0,
width: 0
};
}
return showMask ? _react2["default"].createElement('div', { className: 'drawer-mask', style: maskStyle, onClick: this.fMaskClick }) : null;
};
Drawer.prototype.renderClose = function renderClose() {
var showClose = this.props.showClose;
return showClose ? _react2["default"].createElement(
'i',
{ className: 'drawer-close', onClick: this.fCloseClick },
'\xD7'
) : null;
};
Drawer.prototype.renderBody = function renderBody() {
var _this2 = this;
var _props2 = this.props,
destroyOnClose = _props2.destroyOnClose,
show = _props2.show;
if (destroyOnClose && !show) {
return null;
}
var _props3 = this.props,
hasHeader = _props3.hasHeader,
title = _props3.title,
children = _props3.children,
width = _props3.width,
height = _props3.height,
placement = _props3.placement;
var push = this.state.push;
//抽屉类
var drawerClass = (0, _classnames2["default"])('drawer', 'drawer-' + placement);
//根据位置获取抽屉样式
var translateHideMap = {
left: 'translateX(-100%)',
right: 'translateX(100%)',
top: 'translateY(-100%)',
bottom: 'translateY(100%)'
};
var translateShow = 'translate(0,0)';
if (push) {
var pushNum = 50;
var translateShowMap = {
left: 'translate(' + pushNum + 'px,0)',
right: 'translate(-' + pushNum + 'px,0)',
top: 'translate(0,' + pushNum + 'px)',
bottom: 'translate(0,-' + pushNum + 'px)'
};
translateShow = translateShowMap[placement];
}
var translate = show ? translateShow : translateHideMap[placement];
//抽屉面板样式
if ((0, _common.isNumber)(width)) {
width = width + 'px';
}
if ((0, _common.isNumber)(height)) {
height = height + 'px';
}
if (placement == 'top' || placement == 'bottom') {
if (width == 'auto') {
width = '100%';
}
}
if (placement == 'left' || placement == 'right') {
if (height == 'auto') {
height = '100%';
}
}
var drawerStyle = {
transform: translate,
WebkitTransform: translate,
width: width,
height: height
};
var closer = this.renderClose();
var header = hasHeader ? _react2["default"].createElement(
'div',
{ className: 'drawer-header' },
_react2["default"].createElement(
'div',
{ className: 'drawer-header-title' },
title
)
) : '';
return _react2["default"].createElement(
DrawerContext.Provider,
{ value: this },
_react2["default"].createElement(
'div',
{ ref: function ref(drawer) {
_this2.drawer = drawer;
}, onTransitionEnd: this.fDrawerTransitionEnd, className: drawerClass, style: drawerStyle },
closer,
header,
_react2["default"].createElement(
'div',
{ className: 'drawer-body' },
children
)
)
);
};
Drawer.prototype.renderAll = function renderAll(value) {
var _props4 = this.props,
show = _props4.show,
className = _props4.className,
zIndex = _props4.zIndex;
//容器类
var drawercClass = (0, _classnames2["default"])('drawerc', className);
//容器样式
var drawercStyle = { zIndex: zIndex };
if (show) {
drawercStyle.width = '100%';
} else {
drawercStyle.width = 0;
}
//获取父级抽屉
this.parentDrawer = value;
return _react2["default"].createElement(
'div',
{ className: drawercClass, style: drawercStyle },
this.renderMask(),
this.renderBody()
);
};
Drawer.prototype.render = function render() {
var container = this.props.container;
var conDom = document.querySelector(container);
return _reactDom2["default"].createPortal(_react2["default"].createElement(
DrawerContext.Consumer,
null,
this.renderAll
), conDom);
};
return Drawer;
}(_react.Component);
Drawer.propTypes = propTypes;
Drawer.defaultProps = defaultProps;
exports["default"] = Drawer;
module.exports = exports['default'];
/***/ }),
/* 86 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.bindAll = bindAll;
exports.type = type;
exports.isNumber = isNumber;
function bindAll(context, arrFunc) {
arrFunc.forEach(function (item) {
context[item] = context[item].bind(context);
});
}
function type(obj) {
var toString = Object.prototype.toString;
return toString.call(obj);
}
function isNumber(obj) {
return type(obj) == '[object Number]';
}
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _CSSTransition = _interopRequireDefault(__webpack_require__(88));
var _ReplaceTransition = _interopRequireDefault(__webpack_require__(95));
var _TransitionGroup = _interopRequireDefault(__webpack_require__(96));
var _Transition = _interopRequireDefault(__webpack_require__(92));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = {
Transition: _Transition.default,
TransitionGroup: _TransitionGroup.default,
ReplaceTransition: _ReplaceTransition.default,
CSSTransition: _CSSTransition.default
};
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
exports.__esModule = true;
exports.default = void 0;
var PropTypes = _interopRequireWildcard(__webpack_require__(6));
var _addClass = _interopRequireDefault(__webpack_require__(89));
var _removeClass = _interopRequireDefault(__webpack_require__(91));
var _react = _interopRequireDefault(__webpack_require__(1));
var _Transition = _interopRequireDefault(__webpack_require__(92));
var _PropTypes = __webpack_require__(94);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var addClass = function addClass(node, classes) {
return node && classes && classes.split(' ').forEach(function (c) {
return (0, _addClass.default)(node, c);
});
};
var removeClass = function removeClass(node, classes) {
return node && classes && classes.split(' ').forEach(function (c) {
return (0, _removeClass.default)(node, c);
});
};
/**
* A `Transition` component using CSS transitions and animations.
* It's inspired by the excellent [ng-animate](http://www.nganimate.org/) library.
*
* `CSSTransition` applies a pair of class names during the `appear`, `enter`,
* and `exit` stages of the transition. The first class is applied and then a
* second "active" class in order to activate the css animation. After the animation,
* matching `done` class names are applied to persist the animation state.
*
* When the `in` prop is toggled to `true` the Component will get
* the `example-enter` CSS class and the `example-enter-active` CSS class
* added in the next tick. This is a convention based on the `classNames` prop.
*/
var CSSTransition =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(CSSTransition, _React$Component);
function CSSTransition() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.onEnter = function (node, appearing) {
var _this$getClassNames = _this.getClassNames(appearing ? 'appear' : 'enter'),
className = _this$getClassNames.className;
_this.removeClasses(node, 'exit');
addClass(node, className);
if (_this.props.onEnter) {
_this.props.onEnter(node, appearing);
}
};
_this.onEntering = function (node, appearing) {
var _this$getClassNames2 = _this.getClassNames(appearing ? 'appear' : 'enter'),
activeClassName = _this$getClassNames2.activeClassName;
_this.reflowAndAddClass(node, activeClassName);
if (_this.props.onEntering) {
_this.props.onEntering(node, appearing);
}
};
_this.onEntered = function (node, appearing) {
var _this$getClassNames3 = _this.getClassNames('enter'),
doneClassName = _this$getClassNames3.doneClassName;
_this.removeClasses(node, appearing ? 'appear' : 'enter');
addClass(node, doneClassName);
if (_this.props.onEntered) {
_this.props.onEntered(node, appearing);
}
};
_this.onExit = function (node) {
var _this$getClassNames4 = _this.getClassNames('exit'),
className = _this$getClassNames4.className;
_this.removeClasses(node, 'appear');
_this.removeClasses(node, 'enter');
addClass(node, className);
if (_this.props.onExit) {
_this.props.onExit(node);
}
};
_this.onExiting = function (node) {
var _this$getClassNames5 = _this.getClassNames('exit'),
activeClassName = _this$getClassNames5.activeClassName;
_this.reflowAndAddClass(node, activeClassName);
if (_this.props.onExiting) {
_this.props.onExiting(node);
}
};
_this.onExited = function (node) {
var _this$getClassNames6 = _this.getClassNames('exit'),
doneClassName = _this$getClassNames6.doneClassName;
_this.removeClasses(node, 'exit');
addClass(node, doneClassName);
if (_this.props.onExited) {
_this.props.onExited(node);
}
};
_this.getClassNames = function (type) {
var classNames = _this.props.classNames;
var className = typeof classNames !== 'string' ? classNames[type] : classNames + '-' + type;
var activeClassName = typeof classNames !== 'string' ? classNames[type + 'Active'] : className + '-active';
var doneClassName = typeof classNames !== 'string' ? classNames[type + 'Done'] : className + '-done';
return {
className: className,
activeClassName: activeClassName,
doneClassName: doneClassName
};
};
return _this;
}
var _proto = CSSTransition.prototype;
_proto.removeClasses = function removeClasses(node, type) {
var _this$getClassNames7 = this.getClassNames(type),
className = _this$getClassNames7.className,
activeClassName = _this$getClassNames7.activeClassName,
doneClassName = _this$getClassNames7.doneClassName;
className && removeClass(node, className);
activeClassName && removeClass(node, activeClassName);
doneClassName && removeClass(node, doneClassName);
};
_proto.reflowAndAddClass = function reflowAndAddClass(node, className) {
// This is for to force a repaint,
// which is necessary in order to transition styles when adding a class name.
if (className) {
/* eslint-disable no-unused-expressions */
node && node.scrollTop;
/* eslint-enable no-unused-expressions */
addClass(node, className);
}
};
_proto.render = function render() {
var props = _extends({}, this.props);
delete props.classNames;
return _react.default.createElement(_Transition.default, _extends({}, props, {
onEnter: this.onEnter,
onEntered: this.onEntered,
onEntering: this.onEntering,
onExit: this.onExit,
onExiting: this.onExiting,
onExited: this.onExited
}));
};
return CSSTransition;
}(_react.default.Component);
CSSTransition.propTypes = process.env.NODE_ENV !== "production" ? _extends({}, _Transition.default.propTypes, {
/**
* The animation classNames applied to the component as it enters, exits or has finished the transition.
* A single name can be provided and it will be suffixed for each stage: e.g.
*
* `classNames="fade"` applies `fade-enter`, `fade-enter-active`, `fade-enter-done`,
* `fade-exit`, `fade-exit-active`, `fade-exit-done`, `fade-appear`, and `fade-appear-active`.
* Each individual classNames can also be specified independently like:
*
* ```js
* classNames={{
* appear: 'my-appear',
* appearActive: 'my-active-appear',
* enter: 'my-enter',
* enterActive: 'my-active-enter',
* enterDone: 'my-done-enter',
* exit: 'my-exit',
* exitActive: 'my-active-exit',
* exitDone: 'my-done-exit',
* }}
* ```
*
* If you want to set these classes using CSS Modules:
*
* ```js
* import styles from './styles.css';
* ```
*
* you might want to use camelCase in your CSS file, that way could simply spread
* them instead of listing them one by one:
*
* ```js
* classNames={{ ...styles }}
* ```
*
* @type {string | {
* appear?: string,
* appearActive?: string,
* enter?: string,
* enterActive?: string,
* enterDone?: string,
* exit?: string,
* exitActive?: string,
* exitDone?: string,
* }}
*/
classNames: _PropTypes.classNamesShape,
/**
* A `<Transition>` callback fired immediately after the 'enter' or 'appear' class is
* applied.
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEnter: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'enter-active' or
* 'appear-active' class is applied.
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEntering: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'enter' or
* 'appear' classes are **removed** and the `done` class is added to the DOM node.
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEntered: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'exit' class is
* applied.
*
* @type Function(node: HtmlElement)
*/
onExit: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'exit-active' is applied.
*
* @type Function(node: HtmlElement)
*/
onExiting: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'exit' classes
* are **removed** and the `exit-done` class is added to the DOM node.
*
* @type Function(node: HtmlElement)
*/
onExited: PropTypes.func
}) : {};
var _default = CSSTransition;
exports.default = _default;
module.exports = exports["default"];
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = addClass;
var _hasClass = _interopRequireDefault(__webpack_require__(90));
function addClass(element, className) {
if (element.classList) element.classList.add(className);else if (!(0, _hasClass.default)(element, className)) if (typeof element.className === 'string') element.className = element.className + ' ' + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + ' ' + className);
}
module.exports = exports["default"];
/***/ }),
/* 90 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = hasClass;
function hasClass(element, className) {
if (element.classList) return !!className && element.classList.contains(className);else return (" " + (element.className.baseVal || element.className) + " ").indexOf(" " + className + " ") !== -1;
}
module.exports = exports["default"];
/***/ }),
/* 91 */
/***/ (function(module, exports) {
'use strict';
function replaceClassName(origClass, classToRemove) {
return origClass.replace(new RegExp('(^|\\s)' + classToRemove + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, '');
}
module.exports = function removeClass(element, className) {
if (element.classList) element.classList.remove(className);else if (typeof element.className === 'string') element.className = replaceClassName(element.className, className);else element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));
};
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
exports.__esModule = true;
exports.default = exports.EXITING = exports.ENTERED = exports.ENTERING = exports.EXITED = exports.UNMOUNTED = void 0;
var PropTypes = _interopRequireWildcard(__webpack_require__(6));
var _react = _interopRequireDefault(__webpack_require__(1));
var _reactDom = _interopRequireDefault(__webpack_require__(2));
var _reactLifecyclesCompat = __webpack_require__(93);
var _PropTypes = __webpack_require__(94);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var UNMOUNTED = 'unmounted';
exports.UNMOUNTED = UNMOUNTED;
var EXITED = 'exited';
exports.EXITED = EXITED;
var ENTERING = 'entering';
exports.ENTERING = ENTERING;
var ENTERED = 'entered';
exports.ENTERED = ENTERED;
var EXITING = 'exiting';
/**
* The Transition component lets you describe a transition from one component
* state to another _over time_ with a simple declarative API. Most commonly
* it's used to animate the mounting and unmounting of a component, but can also
* be used to describe in-place transition states as well.
*
* By default the `Transition` component does not alter the behavior of the
* component it renders, it only tracks "enter" and "exit" states for the components.
* It's up to you to give meaning and effect to those states. For example we can
* add styles to a component when it enters or exits:
*
* ```jsx
* import Transition from 'react-transition-group/Transition';
*
* const duration = 300;
*
* const defaultStyle = {
* transition: `opacity ${duration}ms ease-in-out`,
* opacity: 0,
* }
*
* const transitionStyles = {
* entering: { opacity: 0 },
* entered: { opacity: 1 },
* };
*
* const Fade = ({ in: inProp }) => (
* <Transition in={inProp} timeout={duration}>
* {(state) => (
* <div style={{
* ...defaultStyle,
* ...transitionStyles[state]
* }}>
* I'm a fade Transition!
* </div>
* )}
* </Transition>
* );
* ```
*
* As noted the `Transition` component doesn't _do_ anything by itself to its child component.
* What it does do is track transition states over time so you can update the
* component (such as by adding styles or classes) when it changes states.
*
* There are 4 main states a Transition can be in:
* - `'entering'`
* - `'entered'`
* - `'exiting'`
* - `'exited'`
*
* Transition state is toggled via the `in` prop. When `true` the component begins the
* "Enter" stage. During this stage, the component will shift from its current transition state,
* to `'entering'` for the duration of the transition and then to the `'entered'` stage once
* it's complete. Let's take the following example:
*
* ```jsx
* state = { in: false };
*
* toggleEnterState = () => {
* this.setState({ in: true });
* }
*
* render() {
* return (
* <div>
* <Transition in={this.state.in} timeout={500} />
* <button onClick={this.toggleEnterState}>Click to Enter</button>
* </div>
* );
* }
* ```
*
* When the button is clicked the component will shift to the `'entering'` state and
* stay there for 500ms (the value of `timeout`) before it finally switches to `'entered'`.
*
* When `in` is `false` the same thing happens except the state moves from `'exiting'` to `'exited'`.
*
* ## Timing
*
* Timing is often the trickiest part of animation, mistakes can result in slight delays
* that are hard to pin down. A common example is when you want to add an exit transition,
* you should set the desired final styles when the state is `'exiting'`. That's when the
* transition to those styles will start and, if you matched the `timeout` prop with the
* CSS Transition duration, it will end exactly when the state changes to `'exited'`.
*
* > **Note**: For simpler transitions the `Transition` component might be enough, but
* > take into account that it's platform-agnostic, while the `CSSTransition` component
* > [forces reflows](https://github.com/reactjs/react-transition-group/blob/5007303e729a74be66a21c3e2205e4916821524b/src/CSSTransition.js#L208-L215)
* > in order to make more complex transitions more predictable. For example, even though
* > classes `example-enter` and `example-enter-active` are applied immediately one after
* > another, you can still transition from one to the other because of the forced reflow
* > (read [this issue](https://github.com/reactjs/react-transition-group/issues/159#issuecomment-322761171)
* > for more info). Take this into account when choosing between `Transition` and
* > `CSSTransition`.
*/
exports.EXITING = EXITING;
var Transition =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Transition, _React$Component);
function Transition(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
var parentGroup = context.transitionGroup; // In the context of a TransitionGroup all enters are really appears
var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;
var initialStatus;
_this.appearStatus = null;
if (props.in) {
if (appear) {
initialStatus = EXITED;
_this.appearStatus = ENTERING;
} else {
initialStatus = ENTERED;
}
} else {
if (props.unmountOnExit || props.mountOnEnter) {
initialStatus = UNMOUNTED;
} else {
initialStatus = EXITED;
}
}
_this.state = {
status: initialStatus
};
_this.nextCallback = null;
return _this;
}
var _proto = Transition.prototype;
_proto.getChildContext = function getChildContext() {
return {
transitionGroup: null // allows for nested Transitions
};
};
Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {
var nextIn = _ref.in;
if (nextIn && prevState.status === UNMOUNTED) {
return {
status: EXITED
};
}
return null;
}; // getSnapshotBeforeUpdate(prevProps) {
// let nextStatus = null
// if (prevProps !== this.props) {
// const { status } = this.state
// if (this.props.in) {
// if (status !== ENTERING && status !== ENTERED) {
// nextStatus = ENTERING
// }
// } else {
// if (status === ENTERING || status === ENTERED) {
// nextStatus = EXITING
// }
// }
// }
// return { nextStatus }
// }
_proto.componentDidMount = function componentDidMount() {
this.updateStatus(true, this.appearStatus);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var nextStatus = null;
if (prevProps !== this.props) {
var status = this.state.status;
if (this.props.in) {
if (status !== ENTERING && status !== ENTERED) {
nextStatus = ENTERING;
}
} else {
if (status === ENTERING || status === ENTERED) {
nextStatus = EXITING;
}
}
}
this.updateStatus(false, nextStatus);
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.cancelNextCallback();
};
_proto.getTimeouts = function getTimeouts() {
var timeout = this.props.timeout;
var exit, enter, appear;
exit = enter = appear = timeout;
if (timeout != null && typeof timeout !== 'number') {
exit = timeout.exit;
enter = timeout.enter; // TODO: remove fallback for next major
appear = timeout.appear !== undefined ? timeout.appear : enter;
}
return {
exit: exit,
enter: enter,
appear: appear
};
};
_proto.updateStatus = function updateStatus(mounting, nextStatus) {
if (mounting === void 0) {
mounting = false;
}
if (nextStatus !== null) {
// nextStatus will always be ENTERING or EXITING.
this.cancelNextCallback();
var node = _reactDom.default.findDOMNode(this);
if (nextStatus === ENTERING) {
this.performEnter(node, mounting);
} else {
this.performExit(node);
}
} else if (this.props.unmountOnExit && this.state.status === EXITED) {
this.setState({
status: UNMOUNTED
});
}
};
_proto.performEnter = function performEnter(node, mounting) {
var _this2 = this;
var enter = this.props.enter;
var appearing = this.context.transitionGroup ? this.context.transitionGroup.isMounting : mounting;
var timeouts = this.getTimeouts();
var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED
// if we are mounting and running this it means appear _must_ be set
if (!mounting && !enter) {
this.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(node);
});
return;
}
this.props.onEnter(node, appearing);
this.safeSetState({
status: ENTERING
}, function () {
_this2.props.onEntering(node, appearing);
_this2.onTransitionEnd(node, enterTimeout, function () {
_this2.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(node, appearing);
});
});
});
};
_proto.performExit = function performExit(node) {
var _this3 = this;
var exit = this.props.exit;
var timeouts = this.getTimeouts(); // no exit animation skip right to EXITED
if (!exit) {
this.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(node);
});
return;
}
this.props.onExit(node);
this.safeSetState({
status: EXITING
}, function () {
_this3.props.onExiting(node);
_this3.onTransitionEnd(node, timeouts.exit, function () {
_this3.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(node);
});
});
});
};
_proto.cancelNextCallback = function cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
};
_proto.safeSetState = function safeSetState(nextState, callback) {
// This shouldn't be necessary, but there are weird race conditions with
// setState callbacks and unmounting in testing, so always make sure that
// we can cancel any pending setState callbacks after we unmount.
callback = this.setNextCallback(callback);
this.setState(nextState, callback);
};
_proto.setNextCallback = function setNextCallback(callback) {
var _this4 = this;
var active = true;
this.nextCallback = function (event) {
if (active) {
active = false;
_this4.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = function () {
active = false;
};
return this.nextCallback;
};
_proto.onTransitionEnd = function onTransitionEnd(node, timeout, handler) {
this.setNextCallback(handler);
var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;
if (!node || doesNotHaveTimeoutOrListener) {
setTimeout(this.nextCallback, 0);
return;
}
if (this.props.addEndListener) {
this.props.addEndListener(node, this.nextCallback);
}
if (timeout != null) {
setTimeout(this.nextCallback, timeout);
}
};
_proto.render = function render() {
var status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
var _this$props = this.props,
children = _this$props.children,
childProps = _objectWithoutPropertiesLoose(_this$props, ["children"]); // filter props for Transtition
delete childProps.in;
delete childProps.mountOnEnter;
delete childProps.unmountOnExit;
delete childProps.appear;
delete childProps.enter;
delete childProps.exit;
delete childProps.timeout;
delete childProps.addEndListener;
delete childProps.onEnter;
delete childProps.onEntering;
delete childProps.onEntered;
delete childProps.onExit;
delete childProps.onExiting;
delete childProps.onExited;
if (typeof children === 'function') {
return children(status, childProps);
}
var child = _react.default.Children.only(children);
return _react.default.cloneElement(child, childProps);
};
return Transition;
}(_react.default.Component);
Transition.contextTypes = {
transitionGroup: PropTypes.object
};
Transition.childContextTypes = {
transitionGroup: function transitionGroup() {}
};
Transition.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* A `function` child can be used instead of a React element.
* This function is called with the current transition status
* ('entering', 'entered', 'exiting', 'exited', 'unmounted'), which can be used
* to apply context specific props to a component.
*
* ```jsx
* <Transition timeout={150}>
* {(status) => (
* <MyComponent className={`fade fade-${status}`} />
* )}
* </Transition>
* ```
*/
children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,
/**
* Show the component; triggers the enter or exit states
*/
in: PropTypes.bool,
/**
* By default the child component is mounted immediately along with
* the parent `Transition` component. If you want to "lazy mount" the component on the
* first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay
* mounted, even on "exited", unless you also specify `unmountOnExit`.
*/
mountOnEnter: PropTypes.bool,
/**
* By default the child component stays mounted after it reaches the `'exited'` state.
* Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.
*/
unmountOnExit: PropTypes.bool,
/**
* Normally a component is not transitioned if it is shown when the `<Transition>` component mounts.
* If you want to transition on the first mount set `appear` to `true`, and the
* component will transition in as soon as the `<Transition>` mounts.
*
* > Note: there are no specific "appear" states. `appear` only adds an additional `enter` transition.
*/
appear: PropTypes.bool,
/**
* Enable or disable enter transitions.
*/
enter: PropTypes.bool,
/**
* Enable or disable exit transitions.
*/
exit: PropTypes.bool,
/**
* The duration of the transition, in milliseconds.
* Required unless `addEndListener` is provided
*
* You may specify a single timeout for all transitions like: `timeout={500}`,
* or individually like:
*
* ```jsx
* timeout={{
* enter: 300,
* exit: 500,
* appear: 500,
* }}
* ```
*
* If the value of `appear` is not set, then the value from enter is taken.
*
* If the `enter` or `exit` value is `null` or `undefined`, then the timer is set to `0`
*
* @type {number | { enter?: number, exit?: number, appear?: number }}
*/
timeout: function timeout(props) {
var pt = process.env.NODE_ENV !== "production" ? _PropTypes.timeoutsShape : {};;
if (!props.addEndListener) pt = pt.isRequired;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return pt.apply(void 0, [props].concat(args));
},
/**
* Add a custom transition end trigger. Called with the transitioning
* DOM node and a `done` callback. Allows for more fine grained transition end
* logic. **Note:** Timeouts are still used as a fallback if provided.
*
* ```jsx
* addEndListener={(node, done) => {
* // use the css transitionend event to mark the finish of a transition
* node.addEventListener('transitionend', done, false);
* }}
* ```
*/
addEndListener: PropTypes.func,
/**
* Callback fired before the "entering" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* @type Function(node: HtmlElement, isAppearing: bool) -> void
*/
onEnter: PropTypes.func,
/**
* Callback fired after the "entering" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEntering: PropTypes.func,
/**
* Callback fired after the "entered" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* @type Function(node: HtmlElement, isAppearing: bool) -> void
*/
onEntered: PropTypes.func,
/**
* Callback fired before the "exiting" status is applied.
*
* @type Function(node: HtmlElement) -> void
*/
onExit: PropTypes.func,
/**
* Callback fired after the "exiting" status is applied.
*
* @type Function(node: HtmlElement) -> void
*/
onExiting: PropTypes.func,
/**
* Callback fired after the "exited" status is applied.
*
* @type Function(node: HtmlElement) -> void
*/
onExited: PropTypes.func // Name the function so it is clearer in the documentation
} : {};
function noop() {}
Transition.defaultProps = {
in: false,
mountOnEnter: false,
unmountOnExit: false,
appear: false,
enter: true,
exit: true,
onEnter: noop,
onEntering: noop,
onEntered: noop,
onExit: noop,
onExiting: noop,
onExited: noop
};
Transition.UNMOUNTED = 0;
Transition.EXITED = 1;
Transition.ENTERING = 2;
Transition.ENTERED = 3;
Transition.EXITING = 4;
var _default = (0, _reactLifecyclesCompat.polyfill)(Transition);
exports.default = _default;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 93 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function componentWillMount() {
// Call this.constructor.gDSFP to support sub-classes.
var state = this.constructor.getDerivedStateFromProps(this.props, this.state);
if (state !== null && state !== undefined) {
this.setState(state);
}
}
function componentWillReceiveProps(nextProps) {
// Call this.constructor.gDSFP to support sub-classes.
// Use the setState() updater to ensure state isn't stale in certain edge cases.
function updater(prevState) {
var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);
return state !== null && state !== undefined ? state : null;
}
// Binding "this" is important for shallow renderer support.
this.setState(updater.bind(this));
}
function componentWillUpdate(nextProps, nextState) {
try {
var prevProps = this.props;
var prevState = this.state;
this.props = nextProps;
this.state = nextState;
this.__reactInternalSnapshotFlag = true;
this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(
prevProps,
prevState
);
} finally {
this.props = prevProps;
this.state = prevState;
}
}
// React may warn about cWM/cWRP/cWU methods being deprecated.
// Add a flag to suppress these warnings for this special case.
componentWillMount.__suppressDeprecationWarning = true;
componentWillReceiveProps.__suppressDeprecationWarning = true;
componentWillUpdate.__suppressDeprecationWarning = true;
function polyfill(Component) {
var prototype = Component.prototype;
if (!prototype || !prototype.isReactComponent) {
throw new Error('Can only polyfill class components');
}
if (
typeof Component.getDerivedStateFromProps !== 'function' &&
typeof prototype.getSnapshotBeforeUpdate !== 'function'
) {
return Component;
}
// If new component APIs are defined, "unsafe" lifecycles won't be called.
// Error if any of these lifecycles are present,
// Because they would work differently between older and newer (16.3+) versions of React.
var foundWillMountName = null;
var foundWillReceivePropsName = null;
var foundWillUpdateName = null;
if (typeof prototype.componentWillMount === 'function') {
foundWillMountName = 'componentWillMount';
} else if (typeof prototype.UNSAFE_componentWillMount === 'function') {
foundWillMountName = 'UNSAFE_componentWillMount';
}
if (typeof prototype.componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'componentWillReceiveProps';
} else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
}
if (typeof prototype.componentWillUpdate === 'function') {
foundWillUpdateName = 'componentWillUpdate';
} else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {
foundWillUpdateName = 'UNSAFE_componentWillUpdate';
}
if (
foundWillMountName !== null ||
foundWillReceivePropsName !== null ||
foundWillUpdateName !== null
) {
var componentName = Component.displayName || Component.name;
var newApiName =
typeof Component.getDerivedStateFromProps === 'function'
? 'getDerivedStateFromProps()'
: 'getSnapshotBeforeUpdate()';
throw Error(
'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
componentName +
' uses ' +
newApiName +
' but also contains the following legacy lifecycles:' +
(foundWillMountName !== null ? '\n ' + foundWillMountName : '') +
(foundWillReceivePropsName !== null
? '\n ' + foundWillReceivePropsName
: '') +
(foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') +
'\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' +
'https://fb.me/react-async-component-lifecycle-hooks'
);
}
// React <= 16.2 does not support static getDerivedStateFromProps.
// As a workaround, use cWM and cWRP to invoke the new static lifecycle.
// Newer versions of React will ignore these lifecycles if gDSFP exists.
if (typeof Component.getDerivedStateFromProps === 'function') {
prototype.componentWillMount = componentWillMount;
prototype.componentWillReceiveProps = componentWillReceiveProps;
}
// React <= 16.2 does not support getSnapshotBeforeUpdate.
// As a workaround, use cWU to invoke the new lifecycle.
// Newer versions of React will ignore that lifecycle if gSBU exists.
if (typeof prototype.getSnapshotBeforeUpdate === 'function') {
if (typeof prototype.componentDidUpdate !== 'function') {
throw new Error(
'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'
);
}
prototype.componentWillUpdate = componentWillUpdate;
var componentDidUpdate = prototype.componentDidUpdate;
prototype.componentDidUpdate = function componentDidUpdatePolyfill(
prevProps,
prevState,
maybeSnapshot
) {
// 16.3+ will not execute our will-update method;
// It will pass a snapshot value to did-update though.
// Older versions will require our polyfilled will-update value.
// We need to handle both cases, but can't just check for the presence of "maybeSnapshot",
// Because for <= 15.x versions this might be a "prevContext" object.
// We also can't just check "__reactInternalSnapshot",
// Because get-snapshot might return a falsy value.
// So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.
var snapshot = this.__reactInternalSnapshotFlag
? this.__reactInternalSnapshot
: maybeSnapshot;
componentDidUpdate.call(this, prevProps, prevState, snapshot);
};
}
return Component;
}
exports.polyfill = polyfill;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
exports.__esModule = true;
exports.classNamesShape = exports.timeoutsShape = void 0;
var _propTypes = _interopRequireDefault(__webpack_require__(6));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var timeoutsShape = process.env.NODE_ENV !== 'production' ? _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.shape({
enter: _propTypes.default.number,
exit: _propTypes.default.number,
appear: _propTypes.default.number
}).isRequired]) : null;
exports.timeoutsShape = timeoutsShape;
var classNamesShape = process.env.NODE_ENV !== 'production' ? _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.shape({
enter: _propTypes.default.string,
exit: _propTypes.default.string,
active: _propTypes.default.string
}), _propTypes.default.shape({
enter: _propTypes.default.string,
enterDone: _propTypes.default.string,
enterActive: _propTypes.default.string,
exit: _propTypes.default.string,
exitDone: _propTypes.default.string,
exitActive: _propTypes.default.string
})]) : null;
exports.classNamesShape = classNamesShape;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
exports.__esModule = true;
exports.default = void 0;
var _propTypes = _interopRequireDefault(__webpack_require__(6));
var _react = _interopRequireDefault(__webpack_require__(1));
var _reactDom = __webpack_require__(2);
var _TransitionGroup = _interopRequireDefault(__webpack_require__(96));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* The `<ReplaceTransition>` component is a specialized `Transition` component
* that animates between two children.
*
* ```jsx
* <ReplaceTransition in>
* <Fade><div>I appear first</div></Fade>
* <Fade><div>I replace the above</div></Fade>
* </ReplaceTransition>
* ```
*/
var ReplaceTransition =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(ReplaceTransition, _React$Component);
function ReplaceTransition() {
var _this;
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
_this.handleEnter = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _this.handleLifecycle('onEnter', 0, args);
};
_this.handleEntering = function () {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return _this.handleLifecycle('onEntering', 0, args);
};
_this.handleEntered = function () {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return _this.handleLifecycle('onEntered', 0, args);
};
_this.handleExit = function () {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
return _this.handleLifecycle('onExit', 1, args);
};
_this.handleExiting = function () {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
return _this.handleLifecycle('onExiting', 1, args);
};
_this.handleExited = function () {
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
args[_key7] = arguments[_key7];
}
return _this.handleLifecycle('onExited', 1, args);
};
return _this;
}
var _proto = ReplaceTransition.prototype;
_proto.handleLifecycle = function handleLifecycle(handler, idx, originalArgs) {
var _child$props;
var children = this.props.children;
var child = _react.default.Children.toArray(children)[idx];
if (child.props[handler]) (_child$props = child.props)[handler].apply(_child$props, originalArgs);
if (this.props[handler]) this.props[handler]((0, _reactDom.findDOMNode)(this));
};
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
inProp = _this$props.in,
props = _objectWithoutPropertiesLoose(_this$props, ["children", "in"]);
var _React$Children$toArr = _react.default.Children.toArray(children),
first = _React$Children$toArr[0],
second = _React$Children$toArr[1];
delete props.onEnter;
delete props.onEntering;
delete props.onEntered;
delete props.onExit;
delete props.onExiting;
delete props.onExited;
return _react.default.createElement(_TransitionGroup.default, props, inProp ? _react.default.cloneElement(first, {
key: 'first',
onEnter: this.handleEnter,
onEntering: this.handleEntering,
onEntered: this.handleEntered
}) : _react.default.cloneElement(second, {
key: 'second',
onEnter: this.handleExit,
onEntering: this.handleExiting,
onEntered: this.handleExited
}));
};
return ReplaceTransition;
}(_react.default.Component);
ReplaceTransition.propTypes = process.env.NODE_ENV !== "production" ? {
in: _propTypes.default.bool.isRequired,
children: function children(props, propName) {
if (_react.default.Children.count(props[propName]) !== 2) return new Error("\"" + propName + "\" must be exactly two transition components.");
return null;
}
} : {};
var _default = ReplaceTransition;
exports.default = _default;
module.exports = exports["default"];
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
exports.__esModule = true;
exports.default = void 0;
var _propTypes = _interopRequireDefault(__webpack_require__(6));
var _react = _interopRequireDefault(__webpack_require__(1));
var _reactLifecyclesCompat = __webpack_require__(93);
var _ChildMapping = __webpack_require__(97);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
var values = Object.values || function (obj) {
return Object.keys(obj).map(function (k) {
return obj[k];
});
};
var defaultProps = {
component: 'div',
childFactory: function childFactory(child) {
return child;
}
/**
* The `<TransitionGroup>` component manages a set of transition components
* (`<Transition>` and `<CSSTransition>`) in a list. Like with the transition
* components, `<TransitionGroup>` is a state machine for managing the mounting
* and unmounting of components over time.
*
* Consider the example below. As items are removed or added to the TodoList the
* `in` prop is toggled automatically by the `<TransitionGroup>`.
*
* Note that `<TransitionGroup>` does not define any animation behavior!
* Exactly _how_ a list item animates is up to the individual transition
* component. This means you can mix and match animations across different list
* items.
*/
};
var TransitionGroup =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(TransitionGroup, _React$Component);
function TransitionGroup(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
var handleExited = _this.handleExited.bind(_assertThisInitialized(_assertThisInitialized(_this))); // Initial children should all be entering, dependent on appear
_this.state = {
handleExited: handleExited,
firstRender: true
};
return _this;
}
var _proto = TransitionGroup.prototype;
_proto.getChildContext = function getChildContext() {
return {
transitionGroup: {
isMounting: !this.appeared
}
};
};
_proto.componentDidMount = function componentDidMount() {
this.appeared = true;
this.mounted = true;
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.mounted = false;
};
TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {
var prevChildMapping = _ref.children,
handleExited = _ref.handleExited,
firstRender = _ref.firstRender;
return {
children: firstRender ? (0, _ChildMapping.getInitialChildMapping)(nextProps, handleExited) : (0, _ChildMapping.getNextChildMapping)(nextProps, prevChildMapping, handleExited),
firstRender: false
};
};
_proto.handleExited = function handleExited(child, node) {
var currentChildMapping = (0, _ChildMapping.getChildMapping)(this.props.children);
if (child.key in currentChildMapping) return;
if (child.props.onExited) {
child.props.onExited(node);
}
if (this.mounted) {
this.setState(function (state) {
var children = _extends({}, state.children);
delete children[child.key];
return {
children: children
};
});
}
};
_proto.render = function render() {
var _this$props = this.props,
Component = _this$props.component,
childFactory = _this$props.childFactory,
props = _objectWithoutPropertiesLoose(_this$props, ["component", "childFactory"]);
var children = values(this.state.children).map(childFactory);
delete props.appear;
delete props.enter;
delete props.exit;
if (Component === null) {
return children;
}
return _react.default.createElement(Component, props, children);
};
return TransitionGroup;
}(_react.default.Component);
TransitionGroup.childContextTypes = {
transitionGroup: _propTypes.default.object.isRequired
};
TransitionGroup.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* `<TransitionGroup>` renders a `<div>` by default. You can change this
* behavior by providing a `component` prop.
* If you use React v16+ and would like to avoid a wrapping `<div>` element
* you can pass in `component={null}`. This is useful if the wrapping div
* borks your css styles.
*/
component: _propTypes.default.any,
/**
* A set of `<Transition>` components, that are toggled `in` and out as they
* leave. the `<TransitionGroup>` will inject specific transition props, so
* remember to spread them through if you are wrapping the `<Transition>` as
* with our `<Fade>` example.
*
* While this component is meant to make it easier to animate multiple
* `Transition` or `CSSTransition` children, sometimes you want to transition a
* single child by changing its content, e.g. routes, slides, images in a
* carousel etc. In that case you can change the `key` prop of the child
* component along with its content, that way `TransitionGroup` will know that
* it should transition the child.
*/
children: _propTypes.default.node,
/**
* A convenience prop that enables or disables appear animations
* for all children. Note that specifying this will override any defaults set
* on individual children Transitions.
*/
appear: _propTypes.default.bool,
/**
* A convenience prop that enables or disables enter animations
* for all children. Note that specifying this will override any defaults set
* on individual children Transitions.
*/
enter: _propTypes.default.bool,
/**
* A convenience prop that enables or disables exit animations
* for all children. Note that specifying this will override any defaults set
* on individual children Transitions.
*/
exit: _propTypes.default.bool,
/**
* You may need to apply reactive updates to a child as it is exiting.
* This is generally done by using `cloneElement` however in the case of an exiting
* child the element has already been removed and not accessible to the consumer.
*
* If you do need to update a child as it leaves you can provide a `childFactory`
* to wrap every child, even the ones that are leaving.
*
* @type Function(child: ReactElement) -> ReactElement
*/
childFactory: _propTypes.default.func
} : {};
TransitionGroup.defaultProps = defaultProps;
var _default = (0, _reactLifecyclesCompat.polyfill)(TransitionGroup);
exports.default = _default;
module.exports = exports["default"];
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.getChildMapping = getChildMapping;
exports.mergeChildMappings = mergeChildMappings;
exports.getInitialChildMapping = getInitialChildMapping;
exports.getNextChildMapping = getNextChildMapping;
var _react = __webpack_require__(1);
/**
* Given `this.props.children`, return an object mapping key to child.
*
* @param {*} children `this.props.children`
* @return {object} Mapping of key to child
*/
function getChildMapping(children, mapFn) {
var mapper = function mapper(child) {
return mapFn && (0, _react.isValidElement)(child) ? mapFn(child) : child;
};
var result = Object.create(null);
if (children) _react.Children.map(children, function (c) {
return c;
}).forEach(function (child) {
// run the map function here instead so that the key is the computed one
result[child.key] = mapper(child);
});
return result;
}
/**
* When you're adding or removing children some may be added or removed in the
* same render pass. We want to show *both* since we want to simultaneously
* animate elements in and out. This function takes a previous set of keys
* and a new set of keys and merges them with its best guess of the correct
* ordering. In the future we may expose some of the utilities in
* ReactMultiChild to make this easy, but for now React itself does not
* directly have this concept of the union of prevChildren and nextChildren
* so we implement it here.
*
* @param {object} prev prev children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @param {object} next next children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @return {object} a key set that contains all keys in `prev` and all keys
* in `next` in a reasonable order.
*/
function mergeChildMappings(prev, next) {
prev = prev || {};
next = next || {};
function getValueForKey(key) {
return key in next ? next[key] : prev[key];
} // For each key of `next`, the list of keys to insert before that key in
// the combined list
var nextKeysPending = Object.create(null);
var pendingKeys = [];
for (var prevKey in prev) {
if (prevKey in next) {
if (pendingKeys.length) {
nextKeysPending[prevKey] = pendingKeys;
pendingKeys = [];
}
} else {
pendingKeys.push(prevKey);
}
}
var i;
var childMapping = {};
for (var nextKey in next) {
if (nextKeysPending[nextKey]) {
for (i = 0; i < nextKeysPending[nextKey].length; i++) {
var pendingNextKey = nextKeysPending[nextKey][i];
childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);
}
}
childMapping[nextKey] = getValueForKey(nextKey);
} // Finally, add the keys which didn't appear before any key in `next`
for (i = 0; i < pendingKeys.length; i++) {
childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
}
return childMapping;
}
function getProp(child, prop, props) {
return props[prop] != null ? props[prop] : child.props[prop];
}
function getInitialChildMapping(props, onExited) {
return getChildMapping(props.children, function (child) {
return (0, _react.cloneElement)(child, {
onExited: onExited.bind(null, child),
in: true,
appear: getProp(child, 'appear', props),
enter: getProp(child, 'enter', props),
exit: getProp(child, 'exit', props)
});
});
}
function getNextChildMapping(nextProps, prevChildMapping, onExited) {
var nextChildMapping = getChildMapping(nextProps.children);
var children = mergeChildMappings(prevChildMapping, nextChildMapping);
Object.keys(children).forEach(function (key) {
var child = children[key];
if (!(0, _react.isValidElement)(child)) return;
var hasPrev = key in prevChildMapping;
var hasNext = key in nextChildMapping;
var prevChild = prevChildMapping[key];
var isLeaving = (0, _react.isValidElement)(prevChild) && !prevChild.props.in; // item is new (entering)
if (hasNext && (!hasPrev || isLeaving)) {
// console.log('entering', key)
children[key] = (0, _react.cloneElement)(child, {
onExited: onExited.bind(null, child),
in: true,
exit: getProp(child, 'exit', nextProps),
enter: getProp(child, 'enter', nextProps)
});
} else if (!hasNext && hasPrev && !isLeaving) {
// item is old (exiting)
// console.log('leaving', key)
children[key] = (0, _react.cloneElement)(child, {
in: false
});
} else if (hasNext && hasPrev && (0, _react.isValidElement)(prevChild)) {
// item hasn't changed transition states
// copy over the last transition props;
// console.log('unchanged', key)
children[key] = (0, _react.cloneElement)(child, {
onExited: onExited.bind(null, child),
in: prevChild.props.in,
exit: getProp(child, 'exit', nextProps),
enter: getProp(child, 'enter', nextProps)
});
}
});
return children;
}
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Clipboard = __webpack_require__(99);
var _Clipboard2 = _interopRequireDefault(_Clipboard);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Clipboard2["default"];
module.exports = exports['default'];
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _clipboard = __webpack_require__(100);
var _clipboard2 = _interopRequireDefault(_clipboard);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _beeIcon = __webpack_require__(79);
var _beeIcon2 = _interopRequireDefault(_beeIcon);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _beeTooltip = __webpack_require__(108);
var _beeTooltip2 = _interopRequireDefault(_beeTooltip);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _tool = __webpack_require__(132);
var _i18n = __webpack_require__(133);
var _i18n2 = _interopRequireDefault(_i18n);
var _beeModal = __webpack_require__(134);
var _beeModal2 = _interopRequireDefault(_beeModal);
var _beeFormControl = __webpack_require__(266);
var _beeFormControl2 = _interopRequireDefault(_beeFormControl);
var _beeButton = __webpack_require__(264);
var _beeButton2 = _interopRequireDefault(_beeButton);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
//text和target都写的时候target无效。 text的cut改为copy。
// target可以传css3选择器
var propTypes = {
action: _propTypes2["default"].oneOf(['copy', 'cut', null]),
text: _propTypes2["default"].string,
success: _propTypes2["default"].func,
error: _propTypes2["default"].func,
locale: _propTypes2["default"].object
};
var defaultProps = {
action: 'copy',
text: '',
target: '',
success: function success() {},
error: function error() {},
locale: {}
};
var Clipboard = function (_Component) {
_inherits(Clipboard, _Component);
function Clipboard(props, context) {
_classCallCheck(this, Clipboard);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
_this.blur = function () {
_this.setState({
currect: false,
ready: false
});
};
_this.close = function () {
_this.setState({
modalShow: false
});
};
_this.state = {
currect: false,
html: '',
ready: false,
id: 'id' + Math.round(Math.random() * 1000 + 1) + new Date().getTime(),
modalShow: false
};
return _this;
}
Clipboard.prototype.componentWillMount = function componentWillMount() {
var self = this;
var _props = this.props,
success = _props.success,
error = _props.error;
var id = this.state.id;
var cb = new _clipboard2["default"]('#' + id);
cb.on('success', function (e) {
self.setState({
currect: true,
ready: true
});
e.clearSelection();
if (success instanceof Function) success();
});
cb.on('error', function (e) {
self.setState({
modalShow: true,
html: e.text
});
_reactDom2["default"].findDOMNode(self.refs.text).select();
if (error instanceof Function) error();
});
};
Clipboard.prototype.render = function render() {
var _props2 = this.props,
action = _props2.action,
text = _props2.text,
target = _props2.target;
if (text) action = 'copy';
var locale = (0, _tool.getComponentLocale)(this.props, this.context, 'Clipboard', function () {
return _i18n2["default"];
});
var tootipContent = locale[action];
if (this.state.ready) {
tootipContent = locale[action + 'Ready'];
}
return _react2["default"].createElement(
_beeTooltip2["default"],
{ className: 'u-clipboard-tooltip',
overlay: tootipContent,
placement: 'top' },
_react2["default"].createElement(
'span',
{
onMouseOut: this.blur,
className: 'u-clipboard',
id: this.state.id,
'data-clipboard-action': action,
'data-clipboard-target': target,
'data-clipboard-text': text },
this.props.children ? this.props.children : _react2["default"].createElement(_beeIcon2["default"], {
className: (0, _classnames2["default"])({
'uf-correct': this.state.currect,
'uf-copy': !this.state.currect
})
}),
_react2["default"].createElement(
_beeModal2["default"],
{ show: this.state.modalShow, onHide: this.close },
_react2["default"].createElement(
_beeModal2["default"].Header,
{ closeButton: true },
_react2["default"].createElement(
_beeModal2["default"].Title,
null,
' Ctrl+C ',
locale['copyToClipboard'],
' '
)
),
_react2["default"].createElement(
_beeModal2["default"].Body,
null,
_react2["default"].createElement(_beeFormControl2["default"], { ref: 'text', type: 'text', readOnly: true, value: this.state.html })
),
_react2["default"].createElement(
_beeModal2["default"].Footer,
null,
_react2["default"].createElement(
_beeButton2["default"],
{ onClick: this.close },
' ',
locale['close'],
' '
)
)
)
)
);
};
return Clipboard;
}(_react.Component);
;
Clipboard.propTypes = propTypes;
Clipboard.defaultProps = defaultProps;
exports["default"] = Clipboard;
module.exports = exports['default'];
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [module, __webpack_require__(101), __webpack_require__(103), __webpack_require__(104)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports !== "undefined") {
factory(module, require('./clipboard-action'), require('tiny-emitter'), require('good-listener'));
} else {
var mod = {
exports: {}
};
factory(mod, global.clipboardAction, global.tinyEmitter, global.goodListener);
global.clipboard = mod.exports;
}
})(this, function (module, _clipboardAction, _tinyEmitter, _goodListener) {
'use strict';
var _clipboardAction2 = _interopRequireDefault(_clipboardAction);
var _tinyEmitter2 = _interopRequireDefault(_tinyEmitter);
var _goodListener2 = _interopRequireDefault(_goodListener);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Clipboard = function (_Emitter) {
_inherits(Clipboard, _Emitter);
/**
* @param {String|HTMLElement|HTMLCollection|NodeList} trigger
* @param {Object} options
*/
function Clipboard(trigger, options) {
_classCallCheck(this, Clipboard);
var _this = _possibleConstructorReturn(this, (Clipboard.__proto__ || Object.getPrototypeOf(Clipboard)).call(this));
_this.resolveOptions(options);
_this.listenClick(trigger);
return _this;
}
/**
* Defines if attributes would be resolved using internal setter functions
* or custom functions that were passed in the constructor.
* @param {Object} options
*/
_createClass(Clipboard, [{
key: 'resolveOptions',
value: function resolveOptions() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.action = typeof options.action === 'function' ? options.action : this.defaultAction;
this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;
this.text = typeof options.text === 'function' ? options.text : this.defaultText;
this.container = _typeof(options.container) === 'object' ? options.container : document.body;
}
}, {
key: 'listenClick',
value: function listenClick(trigger) {
var _this2 = this;
this.listener = (0, _goodListener2.default)(trigger, 'click', function (e) {
return _this2.onClick(e);
});
}
}, {
key: 'onClick',
value: function onClick(e) {
var trigger = e.delegateTarget || e.currentTarget;
if (this.clipboardAction) {
this.clipboardAction = null;
}
this.clipboardAction = new _clipboardAction2.default({
action: this.action(trigger),
target: this.target(trigger),
text: this.text(trigger),
container: this.container,
trigger: trigger,
emitter: this
});
}
}, {
key: 'defaultAction',
value: function defaultAction(trigger) {
return getAttributeValue('action', trigger);
}
}, {
key: 'defaultTarget',
value: function defaultTarget(trigger) {
var selector = getAttributeValue('target', trigger);
if (selector) {
return document.querySelector(selector);
}
}
}, {
key: 'defaultText',
value: function defaultText(trigger) {
return getAttributeValue('text', trigger);
}
}, {
key: 'destroy',
value: function destroy() {
this.listener.destroy();
if (this.clipboardAction) {
this.clipboardAction.destroy();
this.clipboardAction = null;
}
}
}], [{
key: 'isSupported',
value: function isSupported() {
var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut'];
var actions = typeof action === 'string' ? [action] : action;
var support = !!document.queryCommandSupported;
actions.forEach(function (action) {
support = support && !!document.queryCommandSupported(action);
});
return support;
}
}]);
return Clipboard;
}(_tinyEmitter2.default);
/**
* Helper function to retrieve attribute value.
* @param {String} suffix
* @param {Element} element
*/
function getAttributeValue(suffix, element) {
var attribute = 'data-clipboard-' + suffix;
if (!element.hasAttribute(attribute)) {
return;
}
return element.getAttribute(attribute);
}
module.exports = Clipboard;
});
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [module, __webpack_require__(102)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports !== "undefined") {
factory(module, require('select'));
} else {
var mod = {
exports: {}
};
factory(mod, global.select);
global.clipboardAction = mod.exports;
}
})(this, function (module, _select) {
'use strict';
var _select2 = _interopRequireDefault(_select);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var ClipboardAction = function () {
/**
* @param {Object} options
*/
function ClipboardAction(options) {
_classCallCheck(this, ClipboardAction);
this.resolveOptions(options);
this.initSelection();
}
/**
* Defines base properties passed from constructor.
* @param {Object} options
*/
_createClass(ClipboardAction, [{
key: 'resolveOptions',
value: function resolveOptions() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.action = options.action;
this.container = options.container;
this.emitter = options.emitter;
this.target = options.target;
this.text = options.text;
this.trigger = options.trigger;
this.selectedText = '';
}
}, {
key: 'initSelection',
value: function initSelection() {
if (this.text) {
this.selectFake();
} else if (this.target) {
this.selectTarget();
}
}
}, {
key: 'selectFake',
value: function selectFake() {
var _this = this;
var isRTL = document.documentElement.getAttribute('dir') == 'rtl';
this.removeFake();
this.fakeHandlerCallback = function () {
return _this.removeFake();
};
this.fakeHandler = this.container.addEventListener('click', this.fakeHandlerCallback) || true;
this.fakeElem = document.createElement('textarea');
// Prevent zooming on iOS
this.fakeElem.style.fontSize = '12pt';
// Reset box model
this.fakeElem.style.border = '0';
this.fakeElem.style.padding = '0';
this.fakeElem.style.margin = '0';
// Move element out of screen horizontally
this.fakeElem.style.position = 'absolute';
this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px';
// Move element to the same position vertically
var yPosition = window.pageYOffset || document.documentElement.scrollTop;
this.fakeElem.style.top = yPosition + 'px';
this.fakeElem.setAttribute('readonly', '');
this.fakeElem.value = this.text;
this.container.appendChild(this.fakeElem);
this.selectedText = (0, _select2.default)(this.fakeElem);
this.copyText();
}
}, {
key: 'removeFake',
value: function removeFake() {
if (this.fakeHandler) {
this.container.removeEventListener('click', this.fakeHandlerCallback);
this.fakeHandler = null;
this.fakeHandlerCallback = null;
}
if (this.fakeElem) {
this.container.removeChild(this.fakeElem);
this.fakeElem = null;
}
}
}, {
key: 'selectTarget',
value: function selectTarget() {
this.selectedText = (0, _select2.default)(this.target);
this.copyText();
}
}, {
key: 'copyText',
value: function copyText() {
var succeeded = void 0;
try {
succeeded = document.execCommand(this.action);
} catch (err) {
succeeded = false;
}
this.handleResult(succeeded);
}
}, {
key: 'handleResult',
value: function handleResult(succeeded) {
this.emitter.emit(succeeded ? 'success' : 'error', {
action: this.action,
text: this.selectedText,
trigger: this.trigger,
clearSelection: this.clearSelection.bind(this)
});
}
}, {
key: 'clearSelection',
value: function clearSelection() {
if (this.trigger) {
this.trigger.focus();
}
window.getSelection().removeAllRanges();
}
}, {
key: 'destroy',
value: function destroy() {
this.removeFake();
}
}, {
key: 'action',
set: function set() {
var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'copy';
this._action = action;
if (this._action !== 'copy' && this._action !== 'cut') {
throw new Error('Invalid "action" value, use either "copy" or "cut"');
}
},
get: function get() {
return this._action;
}
}, {
key: 'target',
set: function set(target) {
if (target !== undefined) {
if (target && (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target.nodeType === 1) {
if (this.action === 'copy' && target.hasAttribute('disabled')) {
throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');
}
if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) {
throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');
}
this._target = target;
} else {
throw new Error('Invalid "target" value, use a valid Element');
}
}
},
get: function get() {
return this._target;
}
}]);
return ClipboardAction;
}();
module.exports = ClipboardAction;
});
/***/ }),
/* 102 */
/***/ (function(module, exports) {
function select(element) {
var selectedText;
if (element.nodeName === 'SELECT') {
element.focus();
selectedText = element.value;
}
else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
var isReadOnly = element.hasAttribute('readonly');
if (!isReadOnly) {
element.setAttribute('readonly', '');
}
element.select();
element.setSelectionRange(0, element.value.length);
if (!isReadOnly) {
element.removeAttribute('readonly');
}
selectedText = element.value;
}
else {
if (element.hasAttribute('contenteditable')) {
element.focus();
}
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
selectedText = selection.toString();
}
return selectedText;
}
module.exports = select;
/***/ }),
/* 103 */
/***/ (function(module, exports) {
function E () {
// Keep this empty so it's easier to inherit from
// (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
}
E.prototype = {
on: function (name, callback, ctx) {
var e = this.e || (this.e = {});
(e[name] || (e[name] = [])).push({
fn: callback,
ctx: ctx
});
return this;
},
once: function (name, callback, ctx) {
var self = this;
function listener () {
self.off(name, listener);
callback.apply(ctx, arguments);
};
listener._ = callback
return this.on(name, listener, ctx);
},
emit: function (name) {
var data = [].slice.call(arguments, 1);
var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
var i = 0;
var len = evtArr.length;
for (i; i < len; i++) {
evtArr[i].fn.apply(evtArr[i].ctx, data);
}
return this;
},
off: function (name, callback) {
var e = this.e || (this.e = {});
var evts = e[name];
var liveEvents = [];
if (evts && callback) {
for (var i = 0, len = evts.length; i < len; i++) {
if (evts[i].fn !== callback && evts[i].fn._ !== callback)
liveEvents.push(evts[i]);
}
}
// Remove event from queue to prevent memory leak
// Suggested by https://github.com/lazd
// Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
(liveEvents.length)
? e[name] = liveEvents
: delete e[name];
return this;
}
};
module.exports = E;
module.exports.TinyEmitter = E;
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
var is = __webpack_require__(105);
var delegate = __webpack_require__(106);
/**
* Validates all params and calls the right
* listener function based on its target type.
*
* @param {String|HTMLElement|HTMLCollection|NodeList} target
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listen(target, type, callback) {
if (!target && !type && !callback) {
throw new Error('Missing required arguments');
}
if (!is.string(type)) {
throw new TypeError('Second argument must be a String');
}
if (!is.fn(callback)) {
throw new TypeError('Third argument must be a Function');
}
if (is.node(target)) {
return listenNode(target, type, callback);
}
else if (is.nodeList(target)) {
return listenNodeList(target, type, callback);
}
else if (is.string(target)) {
return listenSelector(target, type, callback);
}
else {
throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');
}
}
/**
* Adds an event listener to a HTML element
* and returns a remove listener function.
*
* @param {HTMLElement} node
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenNode(node, type, callback) {
node.addEventListener(type, callback);
return {
destroy: function() {
node.removeEventListener(type, callback);
}
}
}
/**
* Add an event listener to a list of HTML elements
* and returns a remove listener function.
*
* @param {NodeList|HTMLCollection} nodeList
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenNodeList(nodeList, type, callback) {
Array.prototype.forEach.call(nodeList, function(node) {
node.addEventListener(type, callback);
});
return {
destroy: function() {
Array.prototype.forEach.call(nodeList, function(node) {
node.removeEventListener(type, callback);
});
}
}
}
/**
* Add an event listener to a selector
* and returns a remove listener function.
*
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenSelector(selector, type, callback) {
return delegate(document.body, selector, type, callback);
}
module.exports = listen;
/***/ }),
/* 105 */
/***/ (function(module, exports) {
/**
* Check if argument is a HTML element.
*
* @param {Object} value
* @return {Boolean}
*/
exports.node = function(value) {
return value !== undefined
&& value instanceof HTMLElement
&& value.nodeType === 1;
};
/**
* Check if argument is a list of HTML elements.
*
* @param {Object} value
* @return {Boolean}
*/
exports.nodeList = function(value) {
var type = Object.prototype.toString.call(value);
return value !== undefined
&& (type === '[object NodeList]' || type === '[object HTMLCollection]')
&& ('length' in value)
&& (value.length === 0 || exports.node(value[0]));
};
/**
* Check if argument is a string.
*
* @param {Object} value
* @return {Boolean}
*/
exports.string = function(value) {
return typeof value === 'string'
|| value instanceof String;
};
/**
* Check if argument is a function.
*
* @param {Object} value
* @return {Boolean}
*/
exports.fn = function(value) {
var type = Object.prototype.toString.call(value);
return type === '[object Function]';
};
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
var closest = __webpack_require__(107);
/**
* Delegates event to a selector.
*
* @param {Element} element
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @param {Boolean} useCapture
* @return {Object}
*/
function _delegate(element, selector, type, callback, useCapture) {
var listenerFn = listener.apply(this, arguments);
element.addEventListener(type, listenerFn, useCapture);
return {
destroy: function() {
element.removeEventListener(type, listenerFn, useCapture);
}
}
}
/**
* Delegates event to a selector.
*
* @param {Element|String|Array} [elements]
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @param {Boolean} useCapture
* @return {Object}
*/
function delegate(elements, selector, type, callback, useCapture) {
// Handle the regular Element usage
if (typeof elements.addEventListener === 'function') {
return _delegate.apply(null, arguments);
}
// Handle Element-less usage, it defaults to global delegation
if (typeof type === 'function') {
// Use `document` as the first parameter, then apply arguments
// This is a short way to .unshift `arguments` without running into deoptimizations
return _delegate.bind(null, document).apply(null, arguments);
}
// Handle Selector-based usage
if (typeof elements === 'string') {
elements = document.querySelectorAll(elements);
}
// Handle Array-like based usage
return Array.prototype.map.call(elements, function (element) {
return _delegate(element, selector, type, callback, useCapture);
});
}
/**
* Finds closest match and invokes callback.
*
* @param {Element} element
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @return {Function}
*/
function listener(element, selector, type, callback) {
return function(e) {
e.delegateTarget = closest(e.target, selector);
if (e.delegateTarget) {
callback.call(element, e);
}
}
}
module.exports = delegate;
/***/ }),
/* 107 */
/***/ (function(module, exports) {
var DOCUMENT_NODE_TYPE = 9;
/**
* A polyfill for Element.matches()
*/
if (typeof Element !== 'undefined' && !Element.prototype.matches) {
var proto = Element.prototype;
proto.matches = proto.matchesSelector ||
proto.mozMatchesSelector ||
proto.msMatchesSelector ||
proto.oMatchesSelector ||
proto.webkitMatchesSelector;
}
/**
* Finds the closest parent that matches a selector.
*
* @param {Element} element
* @param {String} selector
* @return {Function}
*/
function closest (element, selector) {
while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
if (typeof element.matches === 'function' &&
element.matches(selector)) {
return element;
}
element = element.parentNode;
}
}
module.exports = closest;
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Tooltip = __webpack_require__(109);
var _Tooltip2 = _interopRequireDefault(_Tooltip);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Tooltip2["default"];
module.exports = exports['default'];
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _OverlayTrigger = __webpack_require__(110);
var _OverlayTrigger2 = _interopRequireDefault(_OverlayTrigger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
/**
* @required
*/
id: _propTypes2["default"].oneOfType([_propTypes2["default"].string, _propTypes2["default"].number]),
inverse: _propTypes2["default"].bool,
visible: _propTypes2["default"].bool,
onVisibleChange: _propTypes2["default"].func,
/**
* 相对目标元素显示上下左右的位置
*/
placement: _propTypes2["default"].oneOf(['top', 'right', 'bottom', 'left', 'topLeft', 'topRight', 'bottomLeft', 'bottomRight', 'leftTop', 'leftBottom', 'rightTop', 'rightBottom']),
/**
* 绝对定位上边距.
*/
positionTop: _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string]),
/**
* 绝对定位左边距
*/
positionLeft: _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string]),
/**
* 与目标Top的距离
*/
arrowOffsetTop: _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string]),
/**
* 与目标Left的距离
*/
arrowOffsetLeft: _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string])
};
var defaultProps = {
placement: 'right',
clsPrefix: 'u-tooltip'
};
function OverlayNode(props) {
var id = props.id,
className = props.className,
classNames = props.classNames,
style = props.style,
overlay = props.overlay,
overlayStyle = props.overlayStyle,
otherProps = props.otherProps;
// style 包含用户传入的自定义样式,以及 bee-overlay 计算返回的样式。
// overlayStyle 是用户传入的自定义样式。
if (overlayStyle && overlayStyle.width) {
style.width = overlayStyle.width;
} else {
delete style.width;
}
return _react2["default"].createElement(
'div',
_extends({
id: id,
role: 'tooltip',
className: (0, _classnames2["default"])(className, classNames),
onMouseEnter: props.onMouseEnter,
onMouseLeave: props.onMouseLeave,
style: style
}, otherProps),
overlay ? _react2["default"].createElement('div', { className: 'tooltip-arrow' }) : '',
overlay ? _react2["default"].createElement(
'div',
{ className: 'tooltip-inner' },
overlay
) : ''
);
}
var Tooltip = function (_React$Component) {
_inherits(Tooltip, _React$Component);
function Tooltip(props) {
_classCallCheck(this, Tooltip);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.onMouseEnter = function () {
var trigger = _this.props.trigger;
if (trigger === 'click') return;
_this.setState({
isHoverShow: true
});
};
_this.onMouseLeave = function () {
var trigger = _this.props.trigger;
if (trigger === 'click') return;
_this.setState({
isHoverShow: false
});
};
_this.handleOnHide = function () {
var onHide = _this.props.onHide;
onHide && onHide(false);
};
var initState = {
isHoverShow: false
};
if ('visible' in props) {
_extends(initState, {
visible: props.visible
});
}
_this.state = initState;
return _this;
}
Tooltip.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var visible = this.props.visible;
if ('visible' in this.props && prevProps.visible !== visible) {
this.setState({
visible: visible
});
}
};
/**
* @desc 鼠标划入时候的事件
*/
/**
* @desc 鼠标划出时候的事件
*/
Tooltip.prototype.render = function render() {
var _classes,
_this2 = this;
var _props = this.props,
placement = _props.placement,
id = _props.id,
arrowOffsetTop = _props.arrowOffsetTop,
arrowOffsetLeft = _props.arrowOffsetLeft,
className = _props.className,
style = _props.style,
children = _props.children,
clsPrefix = _props.clsPrefix,
overlay = _props.overlay,
inverse = _props.inverse,
trigger = _props.trigger,
onVisibleChange = _props.onVisibleChange,
onHide = _props.onHide,
rootClose = _props.rootClose,
visible = _props.visible,
defaultOverlayShown = _props.defaultOverlayShown,
positionTop = _props.positionTop,
positionLeft = _props.positionLeft,
others = _objectWithoutProperties(_props, ['placement', 'id', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children', 'clsPrefix', 'overlay', 'inverse', 'trigger', 'onVisibleChange', 'onHide', 'rootClose', 'visible', 'defaultOverlayShown', 'positionTop', 'positionLeft']);
var classes = (_classes = {}, _defineProperty(_classes, placement, true), _defineProperty(_classes, 'inverse', inverse), _classes);
var arrowStyle = {
top: arrowOffsetTop,
left: arrowOffsetLeft
};
var classNames = (0, _classnames2["default"])(clsPrefix, classes);
var overlayNode = _react2["default"].createElement(OverlayNode, {
id: id,
className: className,
classNames: classNames,
overlay: overlay,
onMouseEnter: this.onMouseEnter,
onMouseLeave: this.onMouseLeave,
style: style,
overlayStyle: style // 用户自定义样式
, arrowOffsetTop: arrowOffsetTop,
arrowOffsetLeft: arrowOffsetLeft,
otherProps: others
});
return 'visible' in this.props ? _react2["default"].createElement(
_OverlayTrigger2["default"],
_extends({}, others, {
visible: this.state.visible,
onVisibleChange: onVisibleChange,
ref: function ref(_ref) {
return _this2.trigger = _ref;
},
shouldUpdatePosition: true,
placement: placement,
overlay: overlayNode,
onHide: this.handleOnHide,
rootClose: rootClose,
defaultOverlayShown: defaultOverlayShown,
positionTop: positionTop,
positionLeft: positionLeft,
trigger: trigger
}),
children
) : _react2["default"].createElement(
_OverlayTrigger2["default"],
_extends({}, others, {
isHoverShow: this.state.isHoverShow,
onVisibleChange: onVisibleChange,
ref: function ref(_ref2) {
return _this2.trigger = _ref2;
},
shouldUpdatePosition: true,
placement: placement,
overlay: overlayNode,
onHide: this.handleOnHide,
rootClose: rootClose,
defaultOverlayShown: defaultOverlayShown,
positionTop: positionTop,
positionLeft: positionLeft,
trigger: trigger
}),
children
);
};
return Tooltip;
}(_react2["default"].Component);
Tooltip.propTypes = propTypes;
Tooltip.defaultProps = defaultProps;
exports["default"] = Tooltip;
module.exports = exports['default'];
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _contains = __webpack_require__(111);
var _contains2 = _interopRequireDefault(_contains);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _warning = __webpack_require__(32);
var _warning2 = _interopRequireDefault(_warning);
var _Portal = __webpack_require__(112);
var _Portal2 = _interopRequireDefault(_Portal);
var _Overlay = __webpack_require__(114);
var _Overlay2 = _interopRequireDefault(_Overlay);
var _createChainedFunction = __webpack_require__(131);
var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var isReact16 = _reactDom2["default"].createPortal !== undefined;
var createPortal = isReact16 ? _reactDom2["default"].createPortal : _reactDom2["default"].unstable_renderSubtreeIntoContainer;
/**
* 检查值是属于这个值,还是等于这个值
*
* @param {string} one
* @param {string|array} of
* @returns {boolean}
*/
function isOneOf(one, of) {
if (Array.isArray(of)) {
return of.indexOf(one) >= 0;
}
return one === of;
}
var triggerType = _propTypes2["default"].oneOf(['click', 'hover', 'focus']);
var propTypes = _extends({}, _Portal2["default"].propTypes, _Overlay2["default"].propTypes, {
/**
* 指定哪些操作或操作触发叠加层可见性
*/
trigger: _propTypes2["default"].oneOfType([triggerType, _propTypes2["default"].arrayOf(triggerType)]),
/**
* 显示和隐藏覆盖一旦触发的毫秒延迟量
*/
delay: _propTypes2["default"].number,
/**
* 触发后显示叠加层之前的延迟毫秒
*/
delayShow: _propTypes2["default"].number,
/**
* 触发后隐藏叠加层的延迟毫秒
*/
delayHide: _propTypes2["default"].number,
// FIXME: This should be `defaultShow`.
/**
* 覆盖的初始可见性状态。对于更细微的可见性控制,请考虑直接使用覆盖组件。
*/
defaultOverlayShown: _propTypes2["default"].bool,
visible: _propTypes2["default"].bool,
/**
* 要覆盖在目标旁边的元素或文本。
*/
overlay: _propTypes2["default"].node.isRequired,
/**
* @private
*/
onBlur: _propTypes2["default"].func,
/**
* @private
*/
onClick: _propTypes2["default"].func,
/**
* @private
*/
onFocus: _propTypes2["default"].func,
/**
* @private
*/
onMouseOut: _propTypes2["default"].func,
/**
* @private
*/
onMouseOver: _propTypes2["default"].func,
// Overridden props from `<Overlay>`.
/**
* @private
*/
target: _propTypes2["default"].oneOf([null]),
/**
* @private
*/
onHide: _propTypes2["default"].oneOf([null]),
/**
* @private
*/
show: _propTypes2["default"].oneOf([null])
});
var defaultProps = {
defaultOverlayShown: false,
trigger: ['hover', 'focus']
};
var OverlayTrigger = function (_Component) {
_inherits(OverlayTrigger, _Component);
function OverlayTrigger(props, context) {
_classCallCheck(this, OverlayTrigger);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
_this.handleToggle = _this.handleToggle.bind(_this);
_this.handleDelayedShow = _this.handleDelayedShow.bind(_this);
_this.handleDelayedHide = _this.handleDelayedHide.bind(_this);
_this.handleHide = _this.handleHide.bind(_this);
_this.makeOverlay = _this.makeOverlay.bind(_this);
_this.handleMouseOver = function (e) {
return _this.handleMouseOverOut(_this.handleDelayedShow, e);
};
_this.handleMouseOut = function (e) {
return _this.handleMouseOverOut(_this.handleDelayedHide, e);
};
_this._mountNode = null;
var visible = void 0;
if ('visible' in props) {
visible = !!props.visible;
} else {
visible = !!props.defaultOverlayShown;
}
_this.state = {
show: visible
};
return _this;
}
OverlayTrigger.prototype.componentDidMount = function componentDidMount() {
this._mountNode = document.createElement('div');
!isReact16 && this.renderOverlay();
};
OverlayTrigger.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
!isReact16 && this.renderOverlay();
if ('visible' in this.props && prevProps.visible !== this.props.visible) {
this.setState({
show: this.props.visible
});
}
if ('isHoverShow' in this.props && prevProps.isHoverShow !== this.props.isHoverShow) {
this.setState({
show: this.props.isHoverShow
});
}
};
OverlayTrigger.prototype.componentWillUnmount = function componentWillUnmount() {
!isReact16 && _reactDom2["default"].unmountComponentAtNode(this._mountNode);
this._mountNode = null;
// 加判断去掉 clearTimeout
this._hoverShowDelay && clearTimeout(this._hoverShowDelay);
this._hoverShowDelay && clearTimeout(this._hoverHideDelay);
};
OverlayTrigger.prototype.handleToggle = function handleToggle() {
if (this.state.show) {
this.hide();
} else {
this.show();
}
};
OverlayTrigger.prototype.handleDelayedShow = function handleDelayedShow() {
var _this2 = this;
if (this._hoverHideDelay != null) {
clearTimeout(this._hoverHideDelay);
this._hoverHideDelay = null;
return;
}
if (this.state.show || this._hoverShowDelay != null) {
return;
}
var delay = this.props.delayShow != null ? this.props.delayShow : this.props.delay;
if (!delay) {
this.show();
return;
}
this._hoverShowDelay = setTimeout(function () {
_this2._hoverShowDelay = null;
_this2.show();
}, delay);
};
OverlayTrigger.prototype.handleDelayedHide = function handleDelayedHide() {
var _this3 = this;
if (this._hoverShowDelay != null) {
clearTimeout(this._hoverShowDelay);
this._hoverShowDelay = null;
return;
}
if (!this.state.show || this._hoverHideDelay != null) {
return;
}
var delay = this.props.delayHide != null ? this.props.delayHide : this.props.delay;
if (!delay) {
this.hide();
return;
}
this._hoverHideDelay = setTimeout(function () {
_this3._hoverHideDelay = null;
_this3.hide();
}, delay);
};
// 简单实现mouseEnter和mouseLeave。
// React的内置版本是有问题的https://github.com/facebook/react/issues/4251
//在触发器被禁用的情况下mouseOut / Over可能导致闪烁
//从一个子元素移动到另一个子元素。
OverlayTrigger.prototype.handleMouseOverOut = function handleMouseOverOut(handler, e) {
var target = e.currentTarget;
var related = e.relatedTarget || e.nativeEvent.toElement;
if (!related || related !== target && !(0, _contains2["default"])(target, related)) {
handler(e);
}
};
OverlayTrigger.prototype.handleHide = function handleHide() {
this.hide();
};
OverlayTrigger.prototype.show = function show() {
this.setState({ show: true });
};
OverlayTrigger.prototype.hide = function hide() {
this.setState({ show: false });
};
OverlayTrigger.prototype.makeOverlay = function makeOverlay(overlay, props) {
return _react2["default"].createElement(
_Overlay2["default"],
_extends({}, props, {
show: this.state.show,
onHide: this.handleHide,
target: this
}),
overlay
);
};
OverlayTrigger.prototype.renderOverlay = function renderOverlay() {
_reactDom2["default"].unstable_renderSubtreeIntoContainer(this, this._overlay, this._mountNode);
};
OverlayTrigger.prototype.render = function render() {
var _props = this.props,
trigger = _props.trigger,
overlay = _props.overlay,
children = _props.children,
onBlur = _props.onBlur,
onClick = _props.onClick,
onFocus = _props.onFocus,
onMouseOut = _props.onMouseOut,
onMouseOver = _props.onMouseOver,
props = _objectWithoutProperties(_props, ['trigger', 'overlay', 'children', 'onBlur', 'onClick', 'onFocus', 'onMouseOut', 'onMouseOver']);
delete props.delay;
delete props.delayShow;
delete props.delayHide;
delete props.defaultOverlayShown;
var child = _react2["default"].Children.only(children);
var childProps = child.props;
var triggerProps = {
'aria-describedby': overlay.props.id
};
// FIXME: 这里用于传递这个组件上的处理程序的逻辑是不一致的。我们不应该通过任何这些道具。
triggerProps.onClick = (0, _createChainedFunction2["default"])(childProps.onClick, onClick);
if (isOneOf('click', trigger) && !('visible' in this.props)) {
triggerProps.onClick = (0, _createChainedFunction2["default"])(triggerProps.onClick, this.handleToggle);
}
if (isOneOf('hover', trigger) && !('visible' in this.props)) {
(0, _warning2["default"])(!(trigger === 'hover'), '[react-bootstrap] Specifying only the `"hover"` trigger limits the ' + 'visibility of the overlay to just mouse users. Consider also ' + 'including the `"focus"` trigger so that touch and keyboard only ' + 'users can see the overlay as well.');
triggerProps.onMouseOver = (0, _createChainedFunction2["default"])(childProps.onMouseOver, onMouseOver, this.handleMouseOver);
triggerProps.onMouseOut = (0, _createChainedFunction2["default"])(childProps.onMouseOut, onMouseOut, this.handleMouseOut);
}
if (isOneOf('focus', trigger) && !('visible' in this.props)) {
triggerProps.onFocus = (0, _createChainedFunction2["default"])(childProps.onFocus, onFocus, this.handleDelayedShow);
triggerProps.onBlur = (0, _createChainedFunction2["default"])(childProps.onBlur, onBlur, this.handleDelayedHide);
}
this._overlay = this.makeOverlay(overlay, props);
if (!isReact16) {
return (0, _react.cloneElement)(child, triggerProps);
}
triggerProps.key = 'overlay';
var portal = _react2["default"].createElement(
_Portal2["default"],
{
key: 'portal',
container: props.container },
this._overlay
);
return [(0, _react.cloneElement)(child, triggerProps), portal];
};
return OverlayTrigger;
}(_react.Component);
OverlayTrigger.propTypes = propTypes;
OverlayTrigger.defaultProps = defaultProps;
exports["default"] = OverlayTrigger;
module.exports = exports['default'];
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = void 0;
var _inDOM = _interopRequireDefault(__webpack_require__(15));
var _default = function () {
// HTML DOM and SVG DOM may have different support levels,
// so we need to check on context instead of a document root element.
return _inDOM.default ? function (context, node) {
if (context.contains) {
return context.contains(node);
} else if (context.compareDocumentPosition) {
return context === node || !!(context.compareDocumentPosition(node) & 16);
} else {
return fallback(context, node);
}
} : fallback;
}();
exports.default = _default;
function fallback(context, node) {
if (node) do {
if (node === context) return true;
} while (node = node.parentNode);
return false;
}
module.exports = exports["default"];
/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _ownerDocument = __webpack_require__(74);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
var _getContainer = __webpack_require__(113);
var _getContainer2 = _interopRequireDefault(_getContainer);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var isReact16 = _reactDom2["default"].createPortal !== undefined;
var createPortal = isReact16 ? _reactDom2["default"].createPortal : _reactDom2["default"].unstable_renderSubtreeIntoContainer;
var propTypes = {
/**
* 存放子组件的容器
*/
container: _propTypes2["default"].oneOfType([_tinperBeeCore.componentOrElement, _propTypes2["default"].func])
};
var defaultProps = {};
/**
* Portal组件是将子组件渲染
*/
var Portal = function (_Component) {
_inherits(Portal, _Component);
function Portal(props) {
_classCallCheck(this, Portal);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.getMountNode = _this.getMountNode.bind(_this);
_this.getOverlayDOMNode = _this.getOverlayDOMNode.bind(_this);
_this.mountOverlayTarget = _this.mountOverlayTarget.bind(_this);
_this.unmountOverlayTarget = _this.unmountOverlayTarget.bind(_this);
_this.renderOverlay = _this.renderOverlay.bind(_this);
_this.unrenderOverlay = _this.unrenderOverlay.bind(_this);
_this.overlayTarget = isReact16 ? document.createElement('div') : null;
return _this;
}
Portal.prototype.componentDidMount = function componentDidMount() {
if (isReact16) {
this.portalContainerNode = (0, _getContainer2["default"])(this.props.container, (0, _ownerDocument2["default"])(this).body);
this.portalContainerNode.appendChild(this.overlayTarget);
} else {
this.renderOverlay();
}
this.mounted = true;
};
Portal.prototype.componentDidUpdate = function componentDidUpdate() {
if (isReact16) {
var overlay = !this.props.children ? null : _react2["default"].Children.only(this.props.children);
if (overlay === null) {
this.unrenderOverlay();
this.unmountOverlayTarget();
} else {}
} else {
this.renderOverlay();
}
};
//this._overlayTarget为当前的要添加的子组件 this._portalContainerNode要添加组件的容器元素
Portal.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.overlayTarget && nextProps.container !== this.props.container) {
this.portalContainerNode.removeChild(this.overlayTarget);
this.portalContainerNode = (0, _getContainer2["default"])(nextProps.container, (0, _ownerDocument2["default"])(this).body);
this.portalContainerNode.appendChild(this.overlayTarget);
}
};
Portal.prototype.componentWillUnmount = function componentWillUnmount() {
this.unrenderOverlay();
this.unmountOverlayTarget();
this.mounted = false;
};
Portal.prototype.getMountNode = function getMountNode() {
return this.overlayTarget;
};
Portal.prototype.getOverlayDOMNode = function getOverlayDOMNode() {
if (!this.mounted) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
if (this.overlayInstance) {
return _reactDom2["default"].findDOMNode(this.overlayInstance);
}
return null;
};
/**
* 如果要添加的子组件不存在就将div添加到要添加容器的DOM中
*/
Portal.prototype.mountOverlayTarget = function mountOverlayTarget() {
if (!this.overlayTarget) {
this.overlayTarget = document.createElement('div');
this.portalContainerNode = (0, _getContainer2["default"])(this.props.container, (0, _ownerDocument2["default"])(this).body);
this.portalContainerNode.appendChild(this.overlayTarget);
}
};
/**
* 将要添加的子元素从容器中移除并把变量置为null
*/
Portal.prototype.unmountOverlayTarget = function unmountOverlayTarget() {
if (this.overlayTarget) {
this.portalContainerNode.removeChild(this.overlayTarget);
this.overlayTarget = null;
}
this.portalContainerNode = null;
};
/**
* 手动渲染_overlayTarget
*/
Portal.prototype.renderOverlay = function renderOverlay() {
var overlay = !this.props.children ? null : _react2["default"].Children.only(this.props.children);
// Save reference for future access.
if (overlay !== null) {
this.mountOverlayTarget();
this.overlayInstance = _reactDom2["default"].unstable_renderSubtreeIntoContainer(this, overlay, this.overlayTarget);
} else {
// Unrender if the component is null for transitions to null
this.unrenderOverlay();
this.unmountOverlayTarget();
}
};
/**
* 销毁_overlayTarget组件。并把_overlayInstance置为null
*/
Portal.prototype.unrenderOverlay = function unrenderOverlay() {
if (this.overlayTarget) {
!isReact16 && _reactDom2["default"].unmountComponentAtNode(this.overlayTarget);
this.overlayInstance = null;
}
};
Portal.prototype.render = function render() {
if (!isReact16) {
return null;
}
var overlay = !this.props.children ? null : _react2["default"].Children.only(this.props.children);
return _reactDom2["default"].createPortal(overlay, this.overlayTarget);
};
return Portal;
}(_react.Component);
;
Portal.propTypes = propTypes;
Portal.defaultProps = defaultProps;
exports["default"] = Portal;
module.exports = exports['default'];
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = getContainer;
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* 获取容器组件
* @param {[type]} container [description]
* @param {[type]} defaultContainer [description]
* @return {[type]} [description]
*/
function getContainer(container, defaultContainer) {
container = typeof container === 'function' ? container() : container;
return _reactDom2["default"].findDOMNode(container) || defaultContainer;
}
module.exports = exports['default'];
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _BaseOverlay = __webpack_require__(115);
var _BaseOverlay2 = _interopRequireDefault(_BaseOverlay);
var _tinperBeeCore = __webpack_require__(27);
var _Fade = __webpack_require__(129);
var _Fade2 = _interopRequireDefault(_Fade);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = _extends({}, _BaseOverlay2["default"].propTypes, {
/**
* 是否显示
*/
show: _propTypes2["default"].bool,
/**
* 是
*/
rootClose: _propTypes2["default"].bool,
/**
* 当点击rootClose触发close时的回调函数
*/
onHide: _propTypes2["default"].func,
/**
* 使用动画
*/
animation: _propTypes2["default"].oneOfType([_tinperBeeCore.elementType, _propTypes2["default"].func]),
/**
* Callback fired before the Overlay transitions in
*/
onEnter: _propTypes2["default"].func,
/**
* Callback fired as the Overlay begins to transition in
*/
onEntering: _propTypes2["default"].func,
/**
* Callback fired after the Overlay finishes transitioning in
*/
onEntered: _propTypes2["default"].func,
/**
* Callback fired right before the Overlay transitions out
*/
onExit: _propTypes2["default"].func,
/**
* Callback fired as the Overlay begins to transition out
*/
onExiting: _propTypes2["default"].func,
/**
* Callback fired after the Overlay finishes transitioning out
*/
onExited: _propTypes2["default"].func,
/**
* Sets the direction of the Overlay.
*/
placement: _propTypes2["default"].oneOf(['top', 'right', 'bottom', 'left']),
/**
* 当Overlay在placement方向放不下时的第二优先级方向
*/
secondPlacement: _propTypes2["default"].oneOf(['top', 'right', 'bottom', 'left'])
});
var defaultProps = {
animation: _Fade2["default"],
rootClose: false,
show: false,
placement: 'right'
};
var Overlay = function (_Component) {
_inherits(Overlay, _Component);
function Overlay() {
_classCallCheck(this, Overlay);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
Overlay.prototype.render = function render() {
var _props = this.props,
animation = _props.animation,
children = _props.children,
props = _objectWithoutProperties(_props, ['animation', 'children']);
var transition = animation === true ? _Fade2["default"] : animation || null;
var child = void 0;
if (!transition) {
child = (0, _react.cloneElement)(children, {
className: (0, _classnames2["default"])(children.props.className, 'in')
});
} else {
child = children;
}
return _react2["default"].createElement(
_BaseOverlay2["default"],
_extends({}, props, {
transition: transition
}),
child
);
};
return Overlay;
}(_react.Component);
Overlay.propTypes = propTypes;
Overlay.defaultProps = defaultProps;
exports["default"] = Overlay;
module.exports = exports['default'];
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _Portal = __webpack_require__(112);
var _Portal2 = _interopRequireDefault(_Portal);
var _Position = __webpack_require__(116);
var _Position2 = _interopRequireDefault(_Position);
var _RootCloseWrapper = __webpack_require__(128);
var _RootCloseWrapper2 = _interopRequireDefault(_RootCloseWrapper);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var isReact16 = _reactDom2["default"].createPortal !== undefined;
var propTypes = _extends({}, _Position2["default"].propTypes, {
/**
* 是否显示
*/
show: _propTypes2["default"].bool,
/**
* 点击其他地方是否隐藏overlay
*/
rootClose: _propTypes2["default"].bool,
/**
* 当rootClose为true的时候触发的隐藏方法
* @type func
*/
onHide: function onHide(props) {
var propType = _propTypes2["default"].func;
if (props.rootClose) {
propType = propType.isRequired;
}
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return propType.apply(undefined, [props].concat(args));
},
/**
* 过渡动画组件
*/
transition: _propTypes2["default"].oneOfType([_tinperBeeCore.elementType, _propTypes2["default"].func]),
/**
* overlay添加动画前的钩子函数
*/
onEnter: _propTypes2["default"].func,
/**
* 开始动画的钩子函数
*/
onEntering: _propTypes2["default"].func,
/**
* 渲染之后的钩子函数
*/
onEntered: _propTypes2["default"].func,
/**
* 关闭开始时的钩子函数
*/
onExit: _propTypes2["default"].func,
/**
* 关闭时的钩子函数
*/
onExiting: _propTypes2["default"].func,
/**
* 关闭后的钩子函数
*/
onExited: _propTypes2["default"].func
});
function noop() {}
var defaultProps = {
show: false,
rootClose: true
};
/**
* 悬浮组件
*/
var BaseOverlay = function (_Component) {
_inherits(BaseOverlay, _Component);
function BaseOverlay(props, context) {
_classCallCheck(this, BaseOverlay);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
_this.state = { exited: !props.show };
_this.onHiddenListener = _this.handleHidden.bind(_this);
return _this;
}
BaseOverlay.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (nextProps.show) {
this.setState({ exited: false });
} else if (!nextProps.transition) {
// Otherwise let handleHidden take care of marking exited.
this.setState({ exited: true });
}
};
BaseOverlay.prototype.handleHidden = function handleHidden() {
this.setState({ exited: true });
if (this.props.onExited) {
var _props;
(_props = this.props).onExited.apply(_props, arguments);
}
};
BaseOverlay.prototype.render = function render() {
var _props2 = this.props,
container = _props2.container,
containerPadding = _props2.containerPadding,
target = _props2.target,
placement = _props2.placement,
secondPlacement = _props2.secondPlacement,
shouldUpdatePosition = _props2.shouldUpdatePosition,
rootClose = _props2.rootClose,
positionLeft = _props2.positionLeft,
positionTop = _props2.positionTop,
children = _props2.children,
Transition = _props2.transition,
props = _objectWithoutProperties(_props2, ['container', 'containerPadding', 'target', 'placement', 'secondPlacement', 'shouldUpdatePosition', 'rootClose', 'positionLeft', 'positionTop', 'children', 'transition']);
// Don't un-render the overlay while it's transitioning out.
var mountOverlay = props.show || Transition && !this.state.exited;
if (!mountOverlay) {
// Don't bother showing anything if we don't have to.
return null;
}
var child = children;
// Position is be inner-most because it adds inline styles into the child,
// which the other wrappers don't forward correctly.
child = _react2["default"].createElement(
_Position2["default"],
{
container: container,
containerPadding: containerPadding,
target: target,
positionLeft: positionLeft,
positionTop: positionTop,
placement: placement,
secondPlacement: secondPlacement,
shouldUpdatePosition: shouldUpdatePosition },
child
);
if (Transition) {
var onExit = props.onExit,
onExiting = props.onExiting,
onEnter = props.onEnter,
onEntering = props.onEntering,
onEntered = props.onEntered;
// This animates the child node by injecting props, so it must precede
// anything that adds a wrapping div.
child = _react2["default"].createElement(
Transition,
{
'in': props.show,
transitionAppear: true,
onExit: onExit,
onExiting: onExiting,
onExited: this.onHiddenListener,
onEnter: onEnter,
onEntering: onEntering,
onEntered: onEntered
},
child
);
}
// This goes after everything else because it adds a wrapping div.
if (rootClose) {
child = _react2["default"].createElement(
_RootCloseWrapper2["default"],
{ onRootClose: props.onHide },
child
);
}
if (isReact16) {
return child;
} else {
return _react2["default"].createElement(
_Portal2["default"],
{ container: container },
child
);
}
};
return BaseOverlay;
}(_react.Component);
BaseOverlay.propTypes = propTypes;
BaseOverlay.defaultProps = defaultProps;
exports["default"] = BaseOverlay;
module.exports = exports['default'];
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _tinperBeeCore = __webpack_require__(27);
var _requestAnimationFrame = __webpack_require__(117);
var _requestAnimationFrame2 = _interopRequireDefault(_requestAnimationFrame);
var _calculatePosition = __webpack_require__(118);
var _calculatePosition2 = _interopRequireDefault(_calculatePosition);
var _getContainer = __webpack_require__(113);
var _getContainer2 = _interopRequireDefault(_getContainer);
var _ownerDocument = __webpack_require__(74);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
var _ownerWindow = __webpack_require__(126);
var _ownerWindow2 = _interopRequireDefault(_ownerWindow);
var _addEventListener = __webpack_require__(76);
var _addEventListener2 = _interopRequireDefault(_addEventListener);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
/**
* 要设置定位的元素
*/
target: _propTypes2["default"].oneOfType([_tinperBeeCore.componentOrElement, _propTypes2["default"].func]),
/**
* 存放的容器元素
*/
container: _propTypes2["default"].oneOfType([_tinperBeeCore.componentOrElement, _propTypes2["default"].func]),
/**
* 容器padding值
*/
containerPadding: _propTypes2["default"].number,
/**
* 位置设置
*/
placement: _propTypes2["default"].oneOf(['top', 'right', 'bottom', 'left']),
/**
* 第二优先级位置设置
*/
secondPlacement: _propTypes2["default"].oneOf(['top', 'right', 'bottom', 'left']),
/**
* 是否需要更新位置
*/
shouldUpdatePosition: _propTypes2["default"].bool
};
var defaultProps = {
containerPadding: 0,
placement: 'right',
shouldUpdatePosition: false
};
/**
* 计算子组件的位置的组件
*/
var Position = function (_Component) {
_inherits(Position, _Component);
function Position(props, context) {
_classCallCheck(this, Position);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
_this.state = {
positionLeft: 0,
positionTop: 0,
arrowOffsetLeft: null,
arrowOffsetTop: null
};
_this.needsFlush = false;
_this.lastTarget = null;
_this.getTarget = _this.getTarget.bind(_this);
_this.maybeUpdatePosition = _this.maybeUpdatePosition.bind(_this);
_this.updatePosition = _this.updatePosition.bind(_this);
_this.onWindowResize = _this.onWindowResize.bind(_this);
return _this;
}
Position.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
this._isMounted = true;
this._windowResizeListener = (0, _addEventListener2["default"])((0, _ownerWindow2["default"])(this), 'resize', function () {
return _this2.onWindowResize();
});
this.updatePosition(this.getTarget());
};
Position.prototype.componentWillReceiveProps = function componentWillReceiveProps() {
this.needsFlush = true;
};
Position.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
if (this.needsFlush) {
this.needsFlush = false;
this.maybeUpdatePosition();
}
};
Position.prototype.componentWillUnmount = function componentWillUnmount() {
this._isMounted = false;
if (this._windowResizeListener) {
this._windowResizeListener.remove();
}
};
/**
* 获取要设置位置的子元素
*/
Position.prototype.getTarget = function getTarget() {
var target = this.props.target;
var targetElement = typeof target === 'function' ? target() : target;
return targetElement && _reactDom2["default"].findDOMNode(targetElement) || null;
};
/**
* 验证是否需要更新位置
*/
Position.prototype.maybeUpdatePosition = function maybeUpdatePosition(placementChanged) {
var target = this.getTarget();
if (!this.props.shouldUpdatePosition && target === this.lastTarget && !placementChanged) {
return;
}
this.updatePosition(target);
};
Position.prototype.onWindowResize = function onWindowResize() {
var _this3 = this;
(0, _requestAnimationFrame2["default"])(function () {
return _this3.updatePosition(_this3.getTarget());
});
};
/**
* 更新位置
*/
Position.prototype.updatePosition = function updatePosition(target) {
var _props = this.props,
placement = _props.placement,
secondPlacement = _props.secondPlacement;
if (!this._isMounted) {
return;
}
this.lastTarget = target;
if (!target) {
this.setState({
positionLeft: 0,
positionTop: 0,
arrowOffsetLeft: null,
arrowOffsetTop: null
});
return;
}
var overlay = _reactDom2["default"].findDOMNode(this);
var container = (0, _getContainer2["default"])(this.props.container, (0, _ownerDocument2["default"])(this).body);
// 若设置了第二渲染位置placement的优先级是 placement > secondPlacement > placement的反方向
if ("secondPlacement" in this.props && secondPlacement) {
var initPosition = (0, _calculatePosition2["default"])(placement, overlay, target, container, this.props.containerPadding);
if (initPosition.inverseArrow) {
var secondPosition = (0, _calculatePosition2["default"])(secondPlacement, overlay, target, container, this.props.containerPadding);
if (secondPosition.inverseArrow) {
this.setState(_extends({}, initPosition, {
renderPlacement: placement
}));
} else {
this.setState(_extends({}, secondPosition, {
renderPlacement: secondPlacement
}));
}
} else {
this.setState(_extends({}, initPosition, {
renderPlacement: placement
}));
}
} else {
this.setState((0, _calculatePosition2["default"])(placement, overlay, target, container, this.props.containerPadding));
}
};
Position.prototype.render = function render() {
var _props2 = this.props,
children = _props2.children,
className = _props2.className,
props = _objectWithoutProperties(_props2, ['children', 'className']);
var _state = this.state,
positionLeft = _state.positionLeft,
positionTop = _state.positionTop,
inverseArrow = _state.inverseArrow,
width = _state.width,
arrowPosition = _objectWithoutProperties(_state, ['positionLeft', 'positionTop', 'inverseArrow', 'width']);
// These should not be forwarded to the child.
delete props.target;
delete props.container;
delete props.containerPadding;
delete props.shouldUpdatePosition;
var child = _react2["default"].Children.only(children);
return (0, _react.cloneElement)(child, _extends({
className: (0, _classnames2["default"])(className, child.props.className, { 'inverse-arrow': inverseArrow })
}, arrowPosition, {
style: _extends({}, child.props.style, {
width: width,
left: positionLeft,
top: positionTop
})
}));
};
return Position;
}(_react.Component);
Position.propTypes = propTypes;
Position.defaultProps = defaultProps;
exports["default"] = Position;
module.exports = exports['default'];
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = void 0;
var _inDOM = _interopRequireDefault(__webpack_require__(15));
var vendors = ['', 'webkit', 'moz', 'o', 'ms'];
var cancel = 'clearTimeout';
var raf = fallback;
var compatRaf;
var getKey = function getKey(vendor, k) {
return vendor + (!vendor ? k : k[0].toUpperCase() + k.substr(1)) + 'AnimationFrame';
};
if (_inDOM.default) {
vendors.some(function (vendor) {
var rafKey = getKey(vendor, 'request');
if (rafKey in window) {
cancel = getKey(vendor, 'cancel');
return raf = function raf(cb) {
return window[rafKey](cb);
};
}
});
}
/* https://github.com/component/raf */
var prev = new Date().getTime();
function fallback(fn) {
var curr = new Date().getTime(),
ms = Math.max(0, 16 - (curr - prev)),
req = setTimeout(fn, ms);
prev = curr;
return req;
}
compatRaf = function compatRaf(cb) {
return raf(cb);
};
compatRaf.cancel = function (id) {
window[cancel] && typeof window[cancel] === 'function' && window[cancel](id);
};
var _default = compatRaf;
exports.default = _default;
module.exports = exports["default"];
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = calculatePosition;
var _offset = __webpack_require__(119);
var _offset2 = _interopRequireDefault(_offset);
var _position = __webpack_require__(121);
var _position2 = _interopRequireDefault(_position);
var _scrollTop = __webpack_require__(124);
var _scrollTop2 = _interopRequireDefault(_scrollTop);
var _ownerDocument = __webpack_require__(74);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function getContainerDimensions(containerNode) {
var width = void 0,
height = void 0,
scroll = void 0;
if (containerNode.tagName === 'BODY') {
width = document.body.scrollWidth;
height = document.body.scrollHeight;
scroll = (0, _scrollTop2["default"])((0, _ownerDocument2["default"])(containerNode).documentElement) || (0, _scrollTop2["default"])(containerNode);
} else {
var _getOffset = (0, _offset2["default"])(containerNode);
width = _getOffset.width;
height = _getOffset.height;
scroll = (0, _scrollTop2["default"])(containerNode);
}
return { width: width, height: height, scroll: scroll };
}
function getTopDelta(top, overlayHeight, container, padding) {
var containerDimensions = getContainerDimensions(container);
var containerScroll = containerDimensions.scroll;
var containerHeight = containerDimensions.height;
var topEdgeOffset = top - padding - containerScroll;
var bottomEdgeOffset = top + padding - containerScroll + overlayHeight;
if (topEdgeOffset < 0) {
return -topEdgeOffset;
} else if (bottomEdgeOffset > containerHeight) {
return containerHeight - bottomEdgeOffset;
} else {
return 0;
}
}
function getLeftDelta(left, overlayWidth, container, padding) {
var containerDimensions = getContainerDimensions(container);
var containerWidth = containerDimensions.width;
var leftEdgeOffset = left - padding;
var rightEdgeOffset = left + padding + overlayWidth;
if (leftEdgeOffset < 0) {
return -leftEdgeOffset;
} else if (rightEdgeOffset > containerWidth) {
return containerWidth - rightEdgeOffset;
}
return 0;
}
function calculatePosition(placement, overlayNode, target, container, padding) {
var childOffset = container.tagName === 'BODY' ? (0, _offset2["default"])(target) : (0, _position2["default"])(target, container);
var _getOffset2 = (0, _offset2["default"])(overlayNode),
overlayHeight = _getOffset2.height,
overlayWidth = _getOffset2.width;
var positionLeft = void 0,
positionTop = void 0,
arrowOffsetLeft = void 0,
arrowOffsetTop = void 0,
inverseArrow = void 0;
if (/^left|^right/.test(placement)) {
positionTop = childOffset.top + (childOffset.height - overlayHeight) / 2;
if (/left/.test(placement)) {
positionLeft = childOffset.left - overlayWidth;
} else {
positionLeft = childOffset.left + childOffset.width;
}
if (/Top/.test(placement)) {
positionTop = childOffset.top;
} else if (/Bottom/.test(placement)) {
positionTop = childOffset.top + childOffset.height - overlayHeight;
}
var topDelta = getTopDelta(positionTop, overlayHeight, container, padding);
var leftDelta = getLeftDelta(positionLeft, overlayWidth, container, padding);
//内容超出
if (leftDelta > 0) {
inverseArrow = true;
positionLeft = childOffset.left + childOffset.width + 6;
} else if (leftDelta < 0) {
inverseArrow = true;
positionLeft = childOffset.left - overlayWidth - 6;
} else {
positionLeft += leftDelta;
}
positionTop += topDelta;
arrowOffsetTop = 50 * (1 - 2 * topDelta / overlayHeight) + '%';
arrowOffsetLeft = void 0;
} else if (/^top|^bottom/.test(placement)) {
positionLeft = childOffset.left + (childOffset.width - overlayWidth) / 2;
if (/top/.test(placement)) {
positionTop = childOffset.top - overlayHeight;
} else {
positionTop = childOffset.top + childOffset.height;
}
if (/Left/.test(placement)) {
positionLeft = childOffset.left;
} else if (/Right/.test(placement)) {
positionLeft = childOffset.left + (childOffset.width - overlayWidth);
}
var _leftDelta = getLeftDelta(positionLeft, overlayWidth, container, padding);
var _topDelta = getTopDelta(positionTop, overlayHeight, container, padding);
positionLeft += _leftDelta;
arrowOffsetLeft = 50 * (1 - 2 * _leftDelta / overlayWidth) + '%';
arrowOffsetTop = void 0;
if (_topDelta > 0) {
inverseArrow = true;
positionTop = childOffset.top + childOffset.height + 6;
} else if (_topDelta < 0) {
inverseArrow = true;
positionTop = childOffset.top - overlayHeight - 6;
} else {
positionTop += _topDelta;
}
// if((positionLeft + panelWidth) > docWidth)
// left = docWidth - panelWidth - 10;
// if(left < 0)
// left = 0;
// if((top + panelHeight) > docHeight) {
// top = docHeight - panelHeight - 10;
// }
// if(top < 0)
// top = 0;
} else {
throw new Error('calcOverlayPosition(): No such placement of "' + placement + '" found.');
}
return { positionLeft: positionLeft, positionTop: positionTop, arrowOffsetLeft: arrowOffsetLeft, arrowOffsetTop: arrowOffsetTop, inverseArrow: inverseArrow, width: overlayWidth };
}
module.exports = exports['default'];
/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = offset;
var _contains = _interopRequireDefault(__webpack_require__(111));
var _isWindow = _interopRequireDefault(__webpack_require__(120));
var _ownerDocument = _interopRequireDefault(__webpack_require__(75));
function offset(node) {
var doc = (0, _ownerDocument.default)(node),
win = (0, _isWindow.default)(doc),
docElem = doc && doc.documentElement,
box = {
top: 0,
left: 0,
height: 0,
width: 0
};
if (!doc) return; // Make sure it's not a disconnected DOM node
if (!(0, _contains.default)(docElem, node)) return box;
if (node.getBoundingClientRect !== undefined) box = node.getBoundingClientRect(); // IE8 getBoundingClientRect doesn't support width & height
box = {
top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0),
width: (box.width == null ? node.offsetWidth : box.width) || 0,
height: (box.height == null ? node.offsetHeight : box.height) || 0
};
return box;
}
module.exports = exports["default"];
/***/ }),
/* 120 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = getWindow;
function getWindow(node) {
return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false;
}
module.exports = exports["default"];
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = position;
var _extends2 = _interopRequireDefault(__webpack_require__(122));
var _offset = _interopRequireDefault(__webpack_require__(119));
var _offsetParent = _interopRequireDefault(__webpack_require__(123));
var _scrollTop = _interopRequireDefault(__webpack_require__(124));
var _scrollLeft = _interopRequireDefault(__webpack_require__(125));
var _style = _interopRequireDefault(__webpack_require__(18));
function nodeName(node) {
return node.nodeName && node.nodeName.toLowerCase();
}
function position(node, offsetParent) {
var parentOffset = {
top: 0,
left: 0
},
offset; // Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ((0, _style.default)(node, 'position') === 'fixed') {
offset = node.getBoundingClientRect();
} else {
offsetParent = offsetParent || (0, _offsetParent.default)(node);
offset = (0, _offset.default)(node);
if (nodeName(offsetParent) !== 'html') parentOffset = (0, _offset.default)(offsetParent);
parentOffset.top += parseInt((0, _style.default)(offsetParent, 'borderTopWidth'), 10) - (0, _scrollTop.default)(offsetParent) || 0;
parentOffset.left += parseInt((0, _style.default)(offsetParent, 'borderLeftWidth'), 10) - (0, _scrollLeft.default)(offsetParent) || 0;
} // Subtract parent offsets and node margins
return (0, _extends2.default)({}, offset, {
top: offset.top - parentOffset.top - (parseInt((0, _style.default)(node, 'marginTop'), 10) || 0),
left: offset.left - parentOffset.left - (parseInt((0, _style.default)(node, 'marginLeft'), 10) || 0)
});
}
module.exports = exports["default"];
/***/ }),
/* 122 */
/***/ (function(module, exports) {
function _extends() {
module.exports = _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
module.exports = _extends;
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = offsetParent;
var _ownerDocument = _interopRequireDefault(__webpack_require__(75));
var _style = _interopRequireDefault(__webpack_require__(18));
function nodeName(node) {
return node.nodeName && node.nodeName.toLowerCase();
}
function offsetParent(node) {
var doc = (0, _ownerDocument.default)(node),
offsetParent = node && node.offsetParent;
while (offsetParent && nodeName(node) !== 'html' && (0, _style.default)(offsetParent, 'position') === 'static') {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || doc.documentElement;
}
module.exports = exports["default"];
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = scrollTop;
var _isWindow = _interopRequireDefault(__webpack_require__(120));
function scrollTop(node, val) {
var win = (0, _isWindow.default)(node);
if (val === undefined) return win ? 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop : node.scrollTop;
if (win) win.scrollTo('pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft, val);else node.scrollTop = val;
}
module.exports = exports["default"];
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = scrollTop;
var _isWindow = _interopRequireDefault(__webpack_require__(120));
function scrollTop(node, val) {
var win = (0, _isWindow.default)(node);
if (val === undefined) return win ? 'pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft : node.scrollLeft;
if (win) win.scrollTo(val, 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop);else node.scrollLeft = val;
}
module.exports = exports["default"];
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = function (componentOrElement) {
return (0, _ownerWindow2["default"])(_reactDom2["default"].findDOMNode(componentOrElement));
};
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _ownerWindow = __webpack_require__(127);
var _ownerWindow2 = _interopRequireDefault(_ownerWindow);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
module.exports = exports['default'];
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = ownerWindow;
var _ownerDocument = _interopRequireDefault(__webpack_require__(75));
function ownerWindow(node) {
var doc = (0, _ownerDocument.default)(node);
return doc && doc.defaultView || doc.parentWindow;
}
module.exports = exports["default"];
/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _contains = __webpack_require__(111);
var _contains2 = _interopRequireDefault(_contains);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _addEventListener = __webpack_require__(76);
var _addEventListener2 = _interopRequireDefault(_addEventListener);
var _ownerDocument = __webpack_require__(74);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
onRootClose: _propTypes2["default"].func,
children: _propTypes2["default"].element,
/**
* 是否禁用
*/
disabled: _propTypes2["default"].bool,
/**
* 触发事件选择
*/
event: _propTypes2["default"].oneOf(['click', 'mousedown'])
};
var defaultProps = {
event: 'click'
};
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
var RootCloseWrapper = function (_Component) {
_inherits(RootCloseWrapper, _Component);
function RootCloseWrapper(props, context) {
_classCallCheck(this, RootCloseWrapper);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
_this.handleMouseCapture = function (e) {
_this.preventMouseRootClose = isModifiedEvent(e) || !isLeftClickEvent(e) || (0, _contains2["default"])(_reactDom2["default"].findDOMNode(_this), e.target);
};
_this.handleMouse = function () {
if (!_this.preventMouseRootClose && _this.props.onRootClose) {
_this.props.onRootClose();
}
};
_this.handleKeyUp = function (e) {
if (e.keyCode === 27 && _this.props.onRootClose) {
_this.props.onRootClose();
}
};
_this.preventMouseRootClose = false;
_this.addEventListeners = _this.addEventListeners.bind(_this);
_this.removeEventListeners = _this.removeEventListeners.bind(_this);
return _this;
}
RootCloseWrapper.prototype.componentDidMount = function componentDidMount() {
if (!this.props.disabled) {
this.addEventListeners();
}
};
RootCloseWrapper.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
if (!this.props.disabled && prevProps.disabled) {
this.addEventListeners();
} else if (this.props.disabled && !prevProps.disabled) {
this.removeEventListeners();
}
};
RootCloseWrapper.prototype.componentWillUnmount = function componentWillUnmount() {
if (!this.props.disabled) {
this.removeEventListeners();
}
};
RootCloseWrapper.prototype.addEventListeners = function addEventListeners() {
var event = this.props.event;
var doc = (0, _ownerDocument2["default"])(this);
// 避免react的监听事件触发引起判断的不准确
this.documentMouseCaptureListener = (0, _addEventListener2["default"])(doc, event, this.handleMouseCapture, true);
this.documentMouseListener = (0, _addEventListener2["default"])(doc, event, this.handleMouse);
this.documentKeyupListener = (0, _addEventListener2["default"])(doc, 'keyup', this.handleKeyUp);
};
RootCloseWrapper.prototype.removeEventListeners = function removeEventListeners() {
if (this.documentMouseCaptureListener) {
this.documentMouseCaptureListener.remove();
}
if (this.documentMouseListener) {
this.documentMouseListener.remove();
}
if (this.documentKeyupListener) {
this.documentKeyupListener.remove();
}
};
RootCloseWrapper.prototype.render = function render() {
return this.props.children;
};
return RootCloseWrapper;
}(_react.Component);
RootCloseWrapper.propTypes = propTypes;
RootCloseWrapper.defaultProps = defaultProps;
exports["default"] = RootCloseWrapper;
module.exports = exports['default'];
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _Transition = __webpack_require__(130);
var _Transition2 = _interopRequireDefault(_Transition);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
/**
* Show the component; triggers the fade in or fade out animation
*/
"in": _propTypes2["default"].bool,
/**
* Unmount the component (remove it from the DOM) when it is faded out
*/
unmountOnExit: _propTypes2["default"].bool,
/**
* Run the fade in animation when the component mounts, if it is initially
* shown
*/
transitionAppear: _propTypes2["default"].bool,
/**
* Duration of the fade animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
timeout: _propTypes2["default"].number,
/**
* Callback fired before the component fades in
*/
onEnter: _propTypes2["default"].func,
/**
* Callback fired after the component starts to fade in
*/
onEntering: _propTypes2["default"].func,
/**
* Callback fired after the has component faded in
*/
onEntered: _propTypes2["default"].func,
/**
* Callback fired before the component fades out
*/
onExit: _propTypes2["default"].func,
/**
* Callback fired after the component starts to fade out
*/
onExiting: _propTypes2["default"].func,
/**
* Callback fired after the component has faded out
*/
onExited: _propTypes2["default"].func
};
var defaultProps = {
"in": false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false
};
var Fade = function (_React$Component) {
_inherits(Fade, _React$Component);
function Fade() {
_classCallCheck(this, Fade);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Fade.prototype.render = function render() {
return _react2["default"].createElement(_Transition2["default"], _extends({}, this.props, {
className: (0, _classnames2["default"])(this.props.className, 'fade'),
enteredClassName: 'in',
enteringClassName: 'in'
}));
};
return Fade;
}(_react2["default"].Component);
Fade.propTypes = propTypes;
Fade.defaultProps = defaultProps;
exports["default"] = Fade;
module.exports = exports['default'];
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EXITING = exports.ENTERED = exports.ENTERING = exports.EXITED = exports.UNMOUNTED = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _properties = __webpack_require__(13);
var _properties2 = _interopRequireDefault(_properties);
var _on = __webpack_require__(16);
var _on2 = _interopRequireDefault(_on);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var transitionEndEvent = _properties2["default"].end;
//设置状态码
var UNMOUNTED = exports.UNMOUNTED = 0;
var EXITED = exports.EXITED = 1;
var ENTERING = exports.ENTERING = 2;
var ENTERED = exports.ENTERED = 3;
var EXITING = exports.EXITING = 4;
var propTypes = {
/**
* 是否触发动画
*/
"in": _propTypes2["default"].bool,
/**
* 不显示的时候是否移除组件
*/
unmountOnExit: _propTypes2["default"].bool,
/**
* 如果设置为默认显示,挂载时显示动画
*/
transitionAppear: _propTypes2["default"].bool,
/**
* 设置超时时间,防止出现问题,可设置为>=动画时间
*/
timeout: _propTypes2["default"].number,
/**
* 退出组件时添加的class
*/
exitedClassName: _propTypes2["default"].string,
/**
* 退出组件中添加的class
*/
exitingClassName: _propTypes2["default"].string,
/**
* 进入动画后添加的class
*/
enteredClassName: _propTypes2["default"].string,
/**
* 进入动画时添加的class
*/
enteringClassName: _propTypes2["default"].string,
/**
* 进入动画开始时的钩子函数
*/
onEnter: _propTypes2["default"].func,
/**
* 进入动画中的钩子函数
*/
onEntering: _propTypes2["default"].func,
/**
* 进入动画后的钩子函数
*/
onEntered: _propTypes2["default"].func,
/**
* 退出动画开始时的钩子函数
*/
onExit: _propTypes2["default"].func,
/**
* 退出动画中的钩子函数
*/
onExiting: _propTypes2["default"].func,
/**
* 退出动画后的钩子函数
*/
onExited: _propTypes2["default"].func
};
function noop() {}
var defaultProps = {
"in": false,
unmountOnExit: false,
transitionAppear: false,
timeout: 5000,
onEnter: noop,
onEntering: noop,
onEntered: noop,
onExit: noop,
onExiting: noop,
onExited: noop
};
/**
* 动画组件
*/
var Transition = function (_Component) {
_inherits(Transition, _Component);
function Transition(props, context) {
_classCallCheck(this, Transition);
var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));
var initialStatus = void 0;
if (props["in"]) {
// 在componentdidmount时开始执行动画
initialStatus = props.transitionAppear ? EXITED : ENTERED;
} else {
initialStatus = props.unmountOnExit ? UNMOUNTED : EXITED;
}
_this.state = { status: initialStatus };
_this.nextCallback = null;
_this.performEnter = _this.performEnter.bind(_this);
_this.performExit = _this.performExit.bind(_this);
_this.cancelNextCallback = _this.cancelNextCallback.bind(_this);
_this.onTransitionEnd = _this.onTransitionEnd.bind(_this);
_this.safeSetState = _this.safeSetState.bind(_this);
_this.setNextCallback = _this.setNextCallback.bind(_this);
return _this;
}
Transition.prototype.componentDidMount = function componentDidMount() {
if (this.props.transitionAppear && this.props["in"]) {
this.performEnter(this.props);
}
};
Transition.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (nextProps["in"] && this.props.unmountOnExit) {
if (this.state.status === UNMOUNTED) {
// 在componentDidUpdate执行动画.
this.setState({ status: EXITED });
}
} else {
this._needsUpdate = true;
}
};
Transition.prototype.componentDidUpdate = function componentDidUpdate() {
var status = this.state.status;
if (this.props.unmountOnExit && status === EXITED) {
// 当使用unmountOnExit时exited为exiting和unmont的过渡状态
if (this.props["in"]) {
this.performEnter(this.props);
} else {
this.setState({ status: UNMOUNTED });
}
return;
}
// 确保只响应prop变化
if (this._needsUpdate) {
this._needsUpdate = false;
if (this.props["in"]) {
if (status === EXITING) {
this.performEnter(this.props);
} else if (status === EXITED) {
this.performEnter(this.props);
}
// 其他,当我们已经输入或输出
} else {
if (status === ENTERING || status === ENTERED) {
this.performExit(this.props);
}
// 我们已经输入或输出完成
}
}
};
Transition.prototype.componentWillUnmount = function componentWillUnmount() {
this.cancelNextCallback();
};
Transition.prototype.performEnter = function performEnter(props) {
var _this2 = this;
this.cancelNextCallback();
var node = _reactDom2["default"].findDOMNode(this);
// 这里接收新props
props.onEnter(node);
this.safeSetState({ status: ENTERING }, function () {
_this2.props.onEntering(node);
_this2.onTransitionEnd(node, function () {
_this2.safeSetState({ status: ENTERED }, function () {
_this2.props.onEntered(node);
});
});
});
};
Transition.prototype.performExit = function performExit(props) {
var _this3 = this;
this.cancelNextCallback();
var node = _reactDom2["default"].findDOMNode(this);
props.onExit(node);
this.safeSetState({ status: EXITING }, function () {
_this3.props.onExiting(node);
_this3.onTransitionEnd(node, function () {
_this3.safeSetState({ status: EXITED }, function () {
_this3.props.onExited(node);
});
});
});
};
Transition.prototype.cancelNextCallback = function cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
};
Transition.prototype.safeSetState = function safeSetState(nextState, callback) {
// 确保在组件销毁后挂起的setState被消除
this.setState(nextState, this.setNextCallback(callback));
};
Transition.prototype.setNextCallback = function setNextCallback(callback) {
var _this4 = this;
var active = true;
this.nextCallback = function (event) {
if (active) {
active = false;
_this4.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = function () {
active = false;
};
return this.nextCallback;
};
Transition.prototype.onTransitionEnd = function onTransitionEnd(node, handler) {
this.setNextCallback(handler);
if (node) {
(0, _on2["default"])(node, transitionEndEvent, this.nextCallback);
setTimeout(this.nextCallback, this.props.timeout);
} else {
setTimeout(this.nextCallback, 0);
}
};
Transition.prototype.render = function render() {
var status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
var _props = this.props,
children = _props.children,
className = _props.className,
childProps = _objectWithoutProperties(_props, ['children', 'className']);
Object.keys(Transition.propTypes).forEach(function (key) {
return delete childProps[key];
});
var transitionClassName = void 0;
if (status === EXITED) {
transitionClassName = this.props.exitedClassName;
} else if (status === ENTERING) {
transitionClassName = this.props.enteringClassName;
} else if (status === ENTERED) {
transitionClassName = this.props.enteredClassName;
} else if (status === EXITING) {
transitionClassName = this.props.exitingClassName;
}
var child = _react2["default"].Children.only(children);
return _react2["default"].cloneElement(child, _extends({}, childProps, {
className: (0, _classnames2["default"])(child.props.className, className, transitionClassName)
}));
};
return Transition;
}(_react.Component);
Transition.propTypes = propTypes;
Transition.defaultProps = defaultProps;
exports["default"] = Transition;
/***/ }),
/* 131 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Safe chained function
*
* Will only create a new function if needed,
* otherwise will pass back existing functions or null.
*
* @param {function} functions to chain
* @returns {function|null}
*/
function createChainedFunction() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return funcs.filter(function (f) {
return f != null;
}).reduce(function (acc, f) {
if (typeof f !== 'function') {
throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.');
}
if (acc === null) {
return f;
}
return function chainedFunction() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
acc.apply(this, args);
f.apply(this, args);
};
}, null);
}
exports["default"] = createChainedFunction;
module.exports = exports['default'];
/***/ }),
/* 132 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.getComponentLocale = getComponentLocale;
exports.getLocaleCode = getLocaleCode;
function getComponentLocale(props, context, componentName, getDefaultLocale) {
var locale = {};
if (context && context.beeLocale && context.beeLocale[componentName]) {
locale = context.beeLocale[componentName];
} else {
var defaultLocale = getDefaultLocale();
locale = defaultLocale["default"] || defaultLocale;
}
var result = _extends({}, locale, props.locale);
if (props.locale) {
result.lang = _extends({}, locale.lang, props.locale.lang);
} else {
result.lang = _extends({}, locale.lang);
}
return result;
}
function getLocaleCode(context) {
var localeCode = context.beeLocale && context.beeLocale.lang;
// Had use LocaleProvide but didn't set locale
if (context.beeLocale && context.beeLocale.exist && !localeCode) {
return 'zh-cn';
}
return localeCode;
}
/***/ }),
/* 133 */
/***/ (function(module, exports) {
'use strict';
module.exports = {
'lang': 'zh-cn',
'copy': '复制',
'cut': '剪切',
'copyReady': '已复制',
'cutReady': '已剪切',
'copyToClipboard': '复制到剪切板',
'close': '关闭',
'en-us': {
'copy': 'Copy',
'cut': 'Cut',
'copyReady': 'Copied',
'cutReady': 'Cut',
'copyToClipboard': 'Copy to Clipboard',
'close': 'Close'
},
'zh-tw': {
'copy': '複製',
'cut': '剪切',
'copyReady': '已複製',
'cutReady': '已剪切',
'copyToClipboard': '複製到剪切板',
'close': '關閉'
}
};
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _Modal = __webpack_require__(135);
var _Modal2 = _interopRequireDefault(_Modal);
var _confirm = __webpack_require__(263);
var _confirm2 = _interopRequireDefault(_confirm);
var _beeIcon = __webpack_require__(79);
var _beeIcon2 = _interopRequireDefault(_beeIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
_Modal2["default"].info = function (props) {
var config = _extends({
type: 'info',
icon: _react2["default"].createElement(_beeIcon2["default"], { type: 'uf-i-c-2' }),
okCancel: false
}, props);
return (0, _confirm2["default"])(config);
};
_Modal2["default"].success = function (props) {
var config = _extends({
type: 'success',
icon: _react2["default"].createElement(_beeIcon2["default"], { type: 'uf-correct' }),
okCancel: false
}, props);
return (0, _confirm2["default"])(config);
};
_Modal2["default"].error = function (props) {
var config = _extends({
type: 'error',
icon: _react2["default"].createElement(_beeIcon2["default"], { type: 'uf-exc-c' }),
okCancel: false
}, props);
return (0, _confirm2["default"])(config);
};
_Modal2["default"].warning = function (props) {
var config = _extends({
type: 'warning',
icon: _react2["default"].createElement(_beeIcon2["default"], { type: 'uf-exc-t' }),
okCancel: false
}, props);
return (0, _confirm2["default"])(config);
};
_Modal2["default"].confirm = function (props) {
var config = _extends({
type: 'confirm',
okCancel: true
}, props);
return (0, _confirm2["default"])(config);
};
_Modal2["default"].destroyAll = function () {
while (_Modal.destroyFns.length) {
var close = _Modal.destroyFns.pop();
if (close) {
close();
}
}
};
exports["default"] = _Modal2["default"];
module.exports = exports['default'];
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.destroyFns = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _extends2;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _events = __webpack_require__(136);
var _events2 = _interopRequireDefault(_events);
var _ownerDocument = __webpack_require__(75);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
var _inDOM = __webpack_require__(15);
var _inDOM2 = _interopRequireDefault(_inDOM);
var _scrollbarSize = __webpack_require__(140);
var _scrollbarSize2 = _interopRequireDefault(_scrollbarSize);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _Modal = __webpack_require__(141);
var _Modal2 = _interopRequireDefault(_Modal);
var _isOverflowing = __webpack_require__(147);
var _isOverflowing2 = _interopRequireDefault(_isOverflowing);
var _tinperBeeCore = __webpack_require__(27);
var _beeTransition = __webpack_require__(11);
var _ModalBody = __webpack_require__(152);
var _ModalBody2 = _interopRequireDefault(_ModalBody);
var _ModalDialog = __webpack_require__(153);
var _ModalDialog2 = _interopRequireDefault(_ModalDialog);
var _ModalFooter = __webpack_require__(260);
var _ModalFooter2 = _interopRequireDefault(_ModalFooter);
var _ModalHeader = __webpack_require__(261);
var _ModalHeader2 = _interopRequireDefault(_ModalHeader);
var _ModalTitle = __webpack_require__(262);
var _ModalTitle2 = _interopRequireDefault(_ModalTitle);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var propTypes = _extends({}, _Modal2["default"].propTypes, _ModalDialog2["default"].propTypes, (_extends2 = {
/**
* 是否弹出遮罩层/遮罩层点击是否触发关闭
*/
backdrop: _propTypes2["default"].oneOf(['static', true, false]),
/**
* 点击遮罩层是否允许关闭
*/
backdropClosable: _propTypes2["default"].bool,
/**
* esc触发关闭
*/
keyboard: _propTypes2["default"].bool,
/**
* 显隐时是否使用动画
*/
animation: _propTypes2["default"].bool,
/**
* 传递给模态框的样式
*/
dialogComponentClass: _tinperBeeCore.elementType,
/**
* 自动设置焦点
*/
autoFocus: _propTypes2["default"].bool,
/**
* 防止打开时焦点离开模态框
*/
enforceFocus: _propTypes2["default"].bool,
/**
* 是否打开模态框
*/
show: _propTypes2["default"].bool,
/**
* 关闭时的钩子函数
*/
onHide: _propTypes2["default"].func,
onEnter: _propTypes2["default"].func,
onEntering: _propTypes2["default"].func,
onEntered: _propTypes2["default"].func,
onExit: _propTypes2["default"].func,
onExiting: _propTypes2["default"].func,
onExited: _propTypes2["default"].func,
containerClassName: _propTypes2["default"].string
}, _defineProperty(_extends2, 'containerClassName', _propTypes2["default"].string), _defineProperty(_extends2, 'container', _Modal2["default"].propTypes.container), _defineProperty(_extends2, 'size', _propTypes2["default"].oneOf(["sm", "lg", "xlg", ""])), _defineProperty(_extends2, 'width', _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string])), _defineProperty(_extends2, 'draggable', _propTypes2["default"].bool), _defineProperty(_extends2, 'resizable', _propTypes2["default"].bool), _defineProperty(_extends2, 'resizeClassName', _propTypes2["default"].string), _defineProperty(_extends2, 'onResizeStart', _propTypes2["default"].func), _defineProperty(_extends2, 'onResize', _propTypes2["default"].func), _defineProperty(_extends2, 'onResizeStop', _propTypes2["default"].func), _defineProperty(_extends2, 'minWidth', _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string])), _defineProperty(_extends2, 'minHeight', _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string])), _defineProperty(_extends2, 'maxWidth', _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string])), _defineProperty(_extends2, 'maxHeight', _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string])), _extends2));
var defaultProps = _extends({}, _Modal2["default"].defaultProps, {
backdropClosable: true,
animation: true,
dialogComponentClass: _ModalDialog2["default"],
draggable: false,
resizable: false,
clsPrefix: 'u-modal'
});
var ModalFuncProps = {
prefixCls: _propTypes2["default"].string,
className: _propTypes2["default"].string,
show: _propTypes2["default"].bool,
title: _react2["default"].ReactNode,
content: _react2["default"].ReactNode,
onOk: _propTypes2["default"].func,
onCancel: _propTypes2["default"].func,
width: _propTypes2["default"].oneOfType([_propTypes2["default"].number, _propTypes2["default"].string]),
okText: _propTypes2["default"].string,
okType: _propTypes2["default"].string,
cancelText: _propTypes2["default"].string,
icon: _react2["default"].ReactNode,
backdrop: _propTypes2["default"].oneOf(['static', true, false])
};
var ModalFunc = function ModalFunc(props) {
destroy = function destroy() {};
update = function update(newConfig) {};
};
var destroyFns = exports.destroyFns = [];
var childContextTypes = {
$u_modal: _propTypes2["default"].shape({
onHide: _propTypes2["default"].func
})
};
var Modal = function (_React$Component) {
_inherits(Modal, _React$Component);
function Modal(props, context) {
_classCallCheck(this, Modal);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleEntering = _this.handleEntering.bind(_this);
_this.handleExited = _this.handleExited.bind(_this);
_this.handleWindowResize = _this.handleWindowResize.bind(_this);
_this.handleDialogClick = _this.handleDialogClick.bind(_this);
_this.state = {
style: {}
};
return _this;
}
Modal.prototype.getChildContext = function getChildContext() {
return {
$u_modal: {
onHide: this.props.onHide
}
};
};
Modal.prototype.componentWillUnmount = function componentWillUnmount() {
// Clean up the listener if we need to.
this.handleExited();
};
Modal.prototype.handleEntering = function handleEntering() {
// FIXME: This should work even when animation is disabled.
_events2["default"].on(window, 'resize', this.handleWindowResize);
this.updateStyle();
};
Modal.prototype.handleExited = function handleExited() {
// FIXME: This should work even when animation is disabled.
_events2["default"].off(window, 'resize', this.handleWindowResize);
};
Modal.prototype.handleWindowResize = function handleWindowResize() {
this.updateStyle();
};
Modal.prototype.handleDialogClick = function handleDialogClick(e) {
if (e.target !== e.currentTarget) {
return;
}
this.props.onHide();
};
Modal.prototype.updateStyle = function updateStyle() {
if (!_inDOM2["default"] || !this._modal) {
return;
}
var dialogNode = this._modal.getDialogElement();
var dialogHeight = dialogNode.scrollHeight;
var document = (0, _ownerDocument2["default"])(dialogNode);
var bodyIsOverflowing = false;
if (this.props.container) {
bodyIsOverflowing = (0, _isOverflowing2["default"])(_reactDom2["default"].findDOMNode(this.props.container));
}
var modalIsOverflowing = dialogHeight > document.documentElement.clientHeight;
this.setState({
style: {
paddingRight: bodyIsOverflowing && !modalIsOverflowing ? (0, _scrollbarSize2["default"])() : undefined,
paddingLeft: !bodyIsOverflowing && modalIsOverflowing ? (0, _scrollbarSize2["default"])() : undefined
}
});
};
Modal.prototype.render = function render() {
var _this2 = this;
var _props = this.props,
backdrop = _props.backdrop,
backdropClosable = _props.backdropClosable,
animation = _props.animation,
show = _props.show,
Dialog = _props.dialogComponentClass,
className = _props.className,
clsPrefix = _props.clsPrefix,
_props$style = _props.style,
style = _props$style === undefined ? {} : _props$style,
size = _props.size,
width = _props.width,
children = _props.children,
onEntering = _props.onEntering,
onExited = _props.onExited,
backdropClassName = _props.backdropClassName,
containerClassName = _props.containerClassName,
draggable = _props.draggable,
resizeClassName = _props.resizeClassName,
props = _objectWithoutProperties(_props, ['backdrop', 'backdropClosable', 'animation', 'show', 'dialogComponentClass', 'className', 'clsPrefix', 'style', 'size', 'width', 'children', 'onEntering', 'onExited', 'backdropClassName', 'containerClassName', 'draggable', 'resizeClassName']);
var _splitComponent = (0, _tinperBeeCore.splitComponent)(props, _Modal2["default"]),
_splitComponent2 = _slicedToArray(_splitComponent, 2),
baseModalProps = _splitComponent2[0],
dialogProps = _splitComponent2[1];
var inClassName = show && !animation && 'in';
var backdropClasses = _defineProperty({}, clsPrefix + '-backdrop', true);
var containerClasses = _defineProperty({}, clsPrefix + '-open', true);
if (Number(width)) width += 'px';
var styleRes = _extends({}, this.state.style, style);
if (width) {
_extends(styleRes, { width: width });
}
return _react2["default"].createElement(
_Modal2["default"],
_extends({}, baseModalProps, {
ref: function ref(c) {
_this2._modal = c;
},
show: show,
onEntering: (0, _tinperBeeCore.createChainedFunction)(onEntering, this.handleEntering),
onExited: (0, _tinperBeeCore.createChainedFunction)(onExited, this.handleExited),
backdrop: backdrop,
backdropClassName: (0, _classnames2["default"])(backdropClasses, inClassName),
containerClassName: (0, _classnames2["default"])(containerClasses, containerClassName),
transition: animation ? _beeTransition.Fade : undefined,
dialogTransitionTimeout: Modal.TRANSITION_DURATION,
backdropTransitionTimeout: Modal.BACKDROP_TRANSITION_DURATION
}),
_react2["default"].createElement(
Dialog,
_extends({}, dialogProps, {
style: styleRes,
className: (0, _classnames2["default"])(className, inClassName, backdropClassName),
onClick: backdrop === true && !!backdropClosable ? this.handleDialogClick : null,
size: size,
draggable: draggable,
resizeClassName: resizeClassName
}),
children
)
);
};
return Modal;
}(_react2["default"].Component);
Modal.info = ModalFunc;
Modal.success = ModalFunc;
Modal.error = ModalFunc;
Modal.warn = ModalFunc;
Modal.warning = ModalFunc;
Modal.confirm = ModalFunc;
Modal.destroyAll = function () {
return;
};
Modal.propTypes = propTypes;
Modal.defaultProps = defaultProps;
Modal.childContextTypes = childContextTypes;
Modal.Body = _ModalBody2["default"];
Modal.Header = _ModalHeader2["default"];
Modal.Title = _ModalTitle2["default"];
Modal.Footer = _ModalFooter2["default"];
Modal.Dialog = _ModalDialog2["default"];
Modal.TRANSITION_DURATION = 200000;
Modal.BACKDROP_TRANSITION_DURATION = 10000;
exports["default"] = Modal;
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = void 0;
var _on = _interopRequireDefault(__webpack_require__(16));
exports.on = _on.default;
var _off = _interopRequireDefault(__webpack_require__(77));
exports.off = _off.default;
var _filter = _interopRequireDefault(__webpack_require__(137));
exports.filter = _filter.default;
var _listen = _interopRequireDefault(__webpack_require__(139));
exports.listen = _listen.default;
var _default = {
on: _on.default,
off: _off.default,
filter: _filter.default,
listen: _listen.default
};
exports.default = _default;
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = filterEvents;
var _contains = _interopRequireDefault(__webpack_require__(111));
var _querySelectorAll = _interopRequireDefault(__webpack_require__(138));
function filterEvents(selector, handler) {
return function filterHandler(e) {
var top = e.currentTarget,
target = e.target,
matches = (0, _querySelectorAll.default)(top, selector);
if (matches.some(function (match) {
return (0, _contains.default)(match, target);
})) handler.call(this, e);
};
}
module.exports = exports["default"];
/***/ }),
/* 138 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = qsa;
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var simpleSelectorRE = /^[\w-]*$/;
var toArray = Function.prototype.bind.call(Function.prototype.call, [].slice);
function qsa(element, selector) {
var maybeID = selector[0] === '#',
maybeClass = selector[0] === '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector,
isSimple = simpleSelectorRE.test(nameOnly),
found;
if (isSimple) {
if (maybeID) {
element = element.getElementById ? element : document;
return (found = element.getElementById(nameOnly)) ? [found] : [];
}
if (element.getElementsByClassName && maybeClass) return toArray(element.getElementsByClassName(nameOnly));
return toArray(element.getElementsByTagName(selector));
}
return toArray(element.querySelectorAll(selector));
}
module.exports = exports["default"];
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = void 0;
var _inDOM = _interopRequireDefault(__webpack_require__(15));
var _on = _interopRequireDefault(__webpack_require__(16));
var _off = _interopRequireDefault(__webpack_require__(77));
var listen = function listen() {};
if (_inDOM.default) {
listen = function listen(node, eventName, handler, capture) {
(0, _on.default)(node, eventName, handler, capture);
return function () {
(0, _off.default)(node, eventName, handler, capture);
};
};
}
var _default = listen;
exports.default = _default;
module.exports = exports["default"];
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = scrollbarSize;
var _inDOM = _interopRequireDefault(__webpack_require__(15));
var size;
function scrollbarSize(recalc) {
if (!size && size !== 0 || recalc) {
if (_inDOM.default) {
var scrollDiv = document.createElement('div');
scrollDiv.style.position = 'absolute';
scrollDiv.style.top = '-9999px';
scrollDiv.style.width = '50px';
scrollDiv.style.height = '50px';
scrollDiv.style.overflow = 'scroll';
document.body.appendChild(scrollDiv);
size = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
}
}
return size;
}
module.exports = exports["default"];
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /*eslint-disable react/prop-types */
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _warning = __webpack_require__(32);
var _warning2 = _interopRequireDefault(_warning);
var _tinperBeeCore = __webpack_require__(27);
var _Portal = __webpack_require__(142);
var _Portal2 = _interopRequireDefault(_Portal);
var _ModalManager = __webpack_require__(145);
var _ModalManager2 = _interopRequireDefault(_ModalManager);
var _ownerDocument = __webpack_require__(143);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
var _addEventListener = __webpack_require__(149);
var _addEventListener2 = _interopRequireDefault(_addEventListener);
var _addFocusListener = __webpack_require__(150);
var _addFocusListener2 = _interopRequireDefault(_addFocusListener);
var _inDOM = __webpack_require__(15);
var _inDOM2 = _interopRequireDefault(_inDOM);
var _activeElement = __webpack_require__(151);
var _activeElement2 = _interopRequireDefault(_activeElement);
var _contains = __webpack_require__(111);
var _contains2 = _interopRequireDefault(_contains);
var _getContainer = __webpack_require__(144);
var _getContainer2 = _interopRequireDefault(_getContainer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var modalManager = new _ModalManager2["default"]();
/**
* 模态框
*/
var propTypes = _extends({}, _Portal2["default"].propTypes, {
/**
* 是否显示
*/
show: _propTypes2["default"].bool,
/**
* 容器
*/
container: _propTypes2["default"].oneOfType([_tinperBeeCore.componentOrElement, _propTypes2["default"].func]),
/**
* 当模态框打开时的钩子函数
*/
onShow: _propTypes2["default"].func,
/**
* 当show参数为false时触发的模态框关闭时的钩子函数
*/
onHide: _propTypes2["default"].func,
/**
* 是否包含背景
*/
backdrop: _propTypes2["default"].oneOfType([_propTypes2["default"].bool, _propTypes2["default"].oneOf(['static'])]),
/**
*返回背景组件的函数
*/
renderBackdrop: _propTypes2["default"].func,
/**
* 设置esc键特殊钩子函数
*/
onEscapeKeyUp: _propTypes2["default"].func,
/**
* 当点击背景时触发的函数
*/
onBackdropClick: _propTypes2["default"].func,
/**
* 背景的style
*/
backdropStyle: _propTypes2["default"].object,
/**
* 背景的class
*/
backdropClassName: _propTypes2["default"].string,
/**
*容器的class
*/
containerClassName: _propTypes2["default"].string,
/**
* 按esc键是否关闭模态框
*/
keyboard: _propTypes2["default"].bool,
/**
* 动画组件
*/
transition: _tinperBeeCore.elementType,
/**
* 设置动画超时时间
*/
dialogTransitionTimeout: _propTypes2["default"].number,
/**
* 设置背景动画超时时间
*/
backdropTransitionTimeout: _propTypes2["default"].number,
/**
* 是否自动设置焦点
*/
autoFocus: _propTypes2["default"].bool,
/**
* 防止焦点离开模态框
*/
enforceFocus: _propTypes2["default"].bool,
/**
* 模态框进入时的钩子函数
*/
onEnter: _propTypes2["default"].func,
/**
* 模态框开始进入时的钩子函数
*/
onEntering: _propTypes2["default"].func,
/**
* 模态框进入后的钩子函数
*/
onEntered: _propTypes2["default"].func,
/**
* 模态框退出时的钩子函数
*/
onExit: _propTypes2["default"].func,
/**
* 模态框开始退出时的钩子函数
*/
onExiting: _propTypes2["default"].func,
/**
* 模态框推出后的钩子函数
*/
onExited: _propTypes2["default"].func,
/**
*管理model状态的实例
*/
manager: _propTypes2["default"].object.isRequired
});
var defaultProps = {
show: false,
backdrop: true,
keyboard: true,
autoFocus: true,
enforceFocus: true,
onHide: function onHide() {},
manager: modalManager,
renderBackdrop: function renderBackdrop(props) {
return _react2["default"].createElement('div', props);
}
};
var BaseModal = function (_Component) {
_inherits(BaseModal, _Component);
function BaseModal(props, content) {
_classCallCheck(this, BaseModal);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.state = {
exited: !_this.props.show
};
_this.onShow = _this.onShow.bind(_this);
_this.onHide = _this.onHide.bind(_this);
_this.setMountNode = _this.setMountNode.bind(_this);
_this.handleHidden = _this.handleHidden.bind(_this);
_this.handleBackdropClick = _this.handleBackdropClick.bind(_this);
_this.handleDocumentKeyUp = _this.handleDocumentKeyUp.bind(_this);
_this.checkForFocus = _this.checkForFocus.bind(_this);
_this.focus = _this.focus.bind(_this);
_this.restoreLastFocus = _this.restoreLastFocus.bind(_this);
_this.enforceFocus = _this.enforceFocus.bind(_this);
_this.getDialogElement = _this.getDialogElement.bind(_this);
_this.isTopModal = _this.isTopModal.bind(_this);
_this.renderBackdrop = _this.renderBackdrop.bind(_this);
return _this;
}
BaseModal.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (nextProps.show) {
this.setState({ exited: false });
} else if (!nextProps.transition) {
// Otherwise let handleHidden take care of marking exited.
this.setState({ exited: true });
}
};
BaseModal.prototype.componentWillUpdate = function componentWillUpdate(nextProps) {
if (!this.props.show && nextProps.show) {
this.checkForFocus();
}
};
BaseModal.prototype.componentDidMount = function componentDidMount() {
if (this.props.show) {
this.onShow();
}
this.mounted = true;
};
BaseModal.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var transition = this.props.transition;
if (prevProps.show && !this.props.show && !transition) {
// Otherwise handleHidden will call this.
this.onHide();
} else if (!prevProps.show && this.props.show) {
this.onShow();
}
};
BaseModal.prototype.componentWillUnmount = function componentWillUnmount() {
var _props = this.props,
show = _props.show,
transition = _props.transition;
if (show || transition && !this.state.exited) {
this.onHide();
}
this.mounted = false;
};
BaseModal.prototype.onShow = function onShow() {
var doc = (0, _ownerDocument2["default"])(this);
var container = (0, _getContainer2["default"])(this.props.container, doc.body);
this.props.manager.add(this, container, this.props.containerClassName);
this._onDocumentKeyupListener = (0, _addEventListener2["default"])(doc, 'keyup', this.handleDocumentKeyUp);
this._onFocusinListener = (0, _addFocusListener2["default"])(this.enforceFocus);
this.focus();
if (this.props.onShow) {
this.props.onShow();
}
};
BaseModal.prototype.onHide = function onHide() {
this.props.manager.remove(this);
this._onDocumentKeyupListener.remove();
this._onFocusinListener.remove();
this.restoreLastFocus();
};
BaseModal.prototype.setMountNode = function setMountNode(ref) {
this.mountNode = ref ? ref.getMountNode() : ref;
};
BaseModal.prototype.handleHidden = function handleHidden() {
this.setState({ exited: true });
this.onHide();
if (this.props.onExited) {
var _props2;
(_props2 = this.props).onExited.apply(_props2, arguments);
}
};
BaseModal.prototype.handleBackdropClick = function handleBackdropClick(e) {
if (e.target !== e.currentTarget) {
return;
}
if (this.props.onBackdropClick) {
this.props.onBackdropClick(e);
}
if (this.props.backdrop === true) {
this.props.onHide();
}
};
BaseModal.prototype.handleDocumentKeyUp = function handleDocumentKeyUp(e) {
if (this.props.keyboard && e.keyCode === 27 && this.isTopModal()) {
if (this.props.onEscapeKeyUp) {
this.props.onEscapeKeyUp(e);
}
this.props.onHide();
}
};
BaseModal.prototype.checkForFocus = function checkForFocus() {
if (_inDOM2["default"]) {
this.lastFocus = (0, _activeElement2["default"])();
}
};
BaseModal.prototype.focus = function focus() {
var autoFocus = this.props.autoFocus;
var modalContent = this.getDialogElement();
var current = (0, _activeElement2["default"])((0, _ownerDocument2["default"])(this));
var focusInModal = current && (0, _contains2["default"])(modalContent, current);
if (modalContent && autoFocus && !focusInModal) {
this.lastFocus = current;
if (!modalContent.hasAttribute('tabIndex')) {
modalContent.setAttribute('tabIndex', -1);
(0, _warning2["default"])(false, 'The modal content node does not accept focus. ' + 'For the benefit of assistive technologies, the tabIndex of the node is being set to "-1".');
}
modalContent.focus();
}
};
BaseModal.prototype.restoreLastFocus = function restoreLastFocus() {
// Support: <=IE11 doesn't support `focus()` on svg elements (RB: #917)
if (this.lastFocus && this.lastFocus.focus) {
this.lastFocus.focus();
this.lastFocus = null;
}
};
BaseModal.prototype.enforceFocus = function enforceFocus() {
var enforceFocus = this.props.enforceFocus;
if (!enforceFocus || !this.mounted || !this.isTopModal()) {
return;
}
var active = (0, _activeElement2["default"])((0, _ownerDocument2["default"])(this));
var modal = this.getDialogElement();
if (modal && modal !== active && !(0, _contains2["default"])(modal, active)) {
modal.focus();
}
};
//instead of a ref, which might conflict with one the parent applied.
BaseModal.prototype.getDialogElement = function getDialogElement() {
var node = this.refs.modal;
return node && node.lastChild;
};
BaseModal.prototype.isTopModal = function isTopModal() {
return this.props.manager.isTopModal(this);
};
BaseModal.prototype.renderBackdrop = function renderBackdrop() {
var _this2 = this;
var _props3 = this.props,
backdropStyle = _props3.backdropStyle,
backdropClassName = _props3.backdropClassName,
renderBackdrop = _props3.renderBackdrop,
Transition = _props3.transition,
backdropTransitionTimeout = _props3.backdropTransitionTimeout;
var backdropRef = function backdropRef(ref) {
return _this2.backdrop = ref;
};
var backdrop = _react2["default"].createElement('div', {
ref: backdropRef,
style: this.props.backdropStyle,
className: this.props.backdropClassName,
onClick: this.handleBackdropClick
});
if (Transition) {
backdrop = _react2["default"].createElement(
Transition,
{ transitionAppear: true,
'in': this.props.show,
timeout: backdropTransitionTimeout
},
renderBackdrop({
ref: backdropRef,
style: backdropStyle,
className: backdropClassName,
onClick: this.handleBackdropClick
})
);
}
return backdrop;
};
BaseModal.prototype.render = function render() {
var _props4 = this.props,
show = _props4.show,
container = _props4.container,
children = _props4.children,
Transition = _props4.transition,
backdrop = _props4.backdrop,
dialogTransitionTimeout = _props4.dialogTransitionTimeout,
className = _props4.className,
style = _props4.style,
onExit = _props4.onExit,
onExiting = _props4.onExiting,
onEnter = _props4.onEnter,
onEntering = _props4.onEntering,
onEntered = _props4.onEntered;
var dialog = _react2["default"].Children.only(children);
var mountModal = show || Transition && !this.state.exited;
if (!mountModal) {
return null;
}
var _dialog$props = dialog.props,
role = _dialog$props.role,
tabIndex = _dialog$props.tabIndex;
if (role === undefined || tabIndex === undefined) {
dialog = (0, _react.cloneElement)(dialog, {
role: role === undefined ? 'document' : role,
tabIndex: tabIndex == null ? '-1' : tabIndex
});
}
if (Transition) {
dialog = _react2["default"].createElement(
Transition,
{
transitionAppear: true,
unmountOnExit: true,
'in': show,
timeout: dialogTransitionTimeout,
onExit: onExit,
onExiting: onExiting,
onExited: this.handleHidden,
onEnter: onEnter,
onEntering: onEntering,
onEntered: onEntered
},
dialog
);
}
return _react2["default"].createElement(
_Portal2["default"],
{
ref: this.setMountNode,
container: container
},
_react2["default"].createElement(
'div',
{
ref: 'modal',
role: role || 'dialog',
style: style,
className: className
},
backdrop && this.renderBackdrop(),
dialog
)
);
};
return BaseModal;
}(_react.Component);
;
BaseModal.Manager = _ModalManager2["default"];
BaseModal.propTypes = propTypes;
BaseModal.defaultProps = defaultProps;
exports["default"] = BaseModal;
module.exports = exports['default'];
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _ownerDocument = __webpack_require__(143);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
var _getContainer = __webpack_require__(144);
var _getContainer2 = _interopRequireDefault(_getContainer);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var isReact16 = _reactDom2["default"].createPortal !== undefined;
var createPortal = isReact16 ? _reactDom2["default"].createPortal : _reactDom2["default"].unstable_renderSubtreeIntoContainer;
var propTypes = {
/**
* 存放子组件的容器
*/
container: _propTypes2["default"].oneOfType([_tinperBeeCore.componentOrElement, _propTypes2["default"].func])
};
var defaultProps = {};
/**
* Portal组件是将子组件渲染
*/
var Portal = function (_Component) {
_inherits(Portal, _Component);
function Portal(props) {
_classCallCheck(this, Portal);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.getMountNode = _this.getMountNode.bind(_this);
_this.getOverlayDOMNode = _this.getOverlayDOMNode.bind(_this);
_this.mountOverlayTarget = _this.mountOverlayTarget.bind(_this);
_this.unmountOverlayTarget = _this.unmountOverlayTarget.bind(_this);
_this.renderOverlay = _this.renderOverlay.bind(_this);
_this.unrenderOverlay = _this.unrenderOverlay.bind(_this);
_this.overlayTarget = isReact16 ? document.createElement('div') : null;
return _this;
}
Portal.prototype.componentDidMount = function componentDidMount() {
if (isReact16) {
this.portalContainerNode = (0, _getContainer2["default"])(this.props.container, (0, _ownerDocument2["default"])(this).body);
this.portalContainerNode.appendChild(this.overlayTarget);
} else {
this.renderOverlay();
}
this.mounted = true;
};
Portal.prototype.componentDidUpdate = function componentDidUpdate() {
if (isReact16) {
var overlay = !this.props.children ? null : _react2["default"].Children.only(this.props.children);
if (overlay === null) {
this.unrenderOverlay();
this.unmountOverlayTarget();
} else {}
} else {
this.renderOverlay();
}
};
//this._overlayTarget为当前的要添加的子组件 this._portalContainerNode要添加组件的容器元素
Portal.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.overlayTarget && nextProps.container !== this.props.container) {
this.portalContainerNode.removeChild(this.overlayTarget);
this.portalContainerNode = (0, _getContainer2["default"])(nextProps.container, (0, _ownerDocument2["default"])(this).body);
this.portalContainerNode.appendChild(this.overlayTarget);
}
};
Portal.prototype.componentWillUnmount = function componentWillUnmount() {
this.unrenderOverlay();
this.unmountOverlayTarget();
this.mounted = false;
};
Portal.prototype.getMountNode = function getMountNode() {
return this.overlayTarget;
};
Portal.prototype.getOverlayDOMNode = function getOverlayDOMNode() {
if (!this.mounted) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
if (this.overlayInstance) {
return _reactDom2["default"].findDOMNode(this.overlayInstance);
}
return null;
};
/**
* 如果要添加的子组件不存在就将div添加到要添加容器的DOM中
*/
Portal.prototype.mountOverlayTarget = function mountOverlayTarget() {
if (!this.overlayTarget) {
this.overlayTarget = document.createElement('div');
this.portalContainerNode = (0, _getContainer2["default"])(this.props.container, (0, _ownerDocument2["default"])(this).body);
this.portalContainerNode.appendChild(this.overlayTarget);
}
};
/**
* 将要添加的子元素从容器中移除并把变量置为null
*/
Portal.prototype.unmountOverlayTarget = function unmountOverlayTarget() {
if (this.overlayTarget) {
this.portalContainerNode.removeChild(this.overlayTarget);
this.overlayTarget = null;
}
this.portalContainerNode = null;
};
/**
* 手动渲染_overlayTarget
*/
Portal.prototype.renderOverlay = function renderOverlay() {
var overlay = !this.props.children ? null : _react2["default"].Children.only(this.props.children);
// Save reference for future access.
if (overlay !== null) {
this.mountOverlayTarget();
this.overlayInstance = _reactDom2["default"].unstable_renderSubtreeIntoContainer(this, overlay, this.overlayTarget);
} else {
// Unrender if the component is null for transitions to null
this.unrenderOverlay();
this.unmountOverlayTarget();
}
};
/**
* 销毁_overlayTarget组件。并把_overlayInstance置为null
*/
Portal.prototype.unrenderOverlay = function unrenderOverlay() {
if (this.overlayTarget) {
!isReact16 && _reactDom2["default"].unmountComponentAtNode(this.overlayTarget);
this.overlayInstance = null;
}
};
Portal.prototype.render = function render() {
if (!isReact16) {
return null;
}
var overlay = !this.props.children ? null : _react2["default"].Children.only(this.props.children);
return _reactDom2["default"].createPortal(overlay, this.overlayTarget);
};
return Portal;
}(_react.Component);
;
Portal.propTypes = propTypes;
Portal.defaultProps = defaultProps;
exports["default"] = Portal;
module.exports = exports['default'];
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = function (componentOrElement) {
return (0, _ownerDocument2["default"])(_reactDom2["default"].findDOMNode(componentOrElement));
};
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _ownerDocument = __webpack_require__(75);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
module.exports = exports['default'];
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = getContainer;
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* 获取容器组件
* @param {[type]} container [description]
* @param {[type]} defaultContainer [description]
* @return {[type]} [description]
*/
function getContainer(container, defaultContainer) {
container = typeof container === 'function' ? container() : container;
return _reactDom2["default"].findDOMNode(container) || defaultContainer;
}
module.exports = exports['default'];
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _style = __webpack_require__(18);
var _style2 = _interopRequireDefault(_style);
var _class = __webpack_require__(146);
var _class2 = _interopRequireDefault(_class);
var _scrollbarSize = __webpack_require__(140);
var _scrollbarSize2 = _interopRequireDefault(_scrollbarSize);
var _isOverflowing = __webpack_require__(147);
var _isOverflowing2 = _interopRequireDefault(_isOverflowing);
var _manageAriaHidden = __webpack_require__(148);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function findIndexOf(arr, cb) {
var idx = -1;
arr.some(function (d, i) {
if (cb(d, i)) {
idx = i;
return true;
}
});
return idx;
}
//查找容器
function findContainer(data, modal) {
return findIndexOf(data, function (d) {
return d.modals.indexOf(modal) !== -1;
});
}
//设置容器style
function setContainerStyle(state, container) {
var style = { overflow: 'hidden' };
state.style = {
overflow: container.style.overflow,
paddingRight: container.style.paddingRight
};
if (state.overflowing) {
//设置内边距,和添加滚动条宽度
style.paddingRight = parseInt((0, _style2["default"])(container, 'paddingRight') || 0, 10) + (0, _scrollbarSize2["default"])() + 'px';
}
(0, _style2["default"])(container, style);
}
//移除容器style
function removeContainerStyle(_ref, container) {
var style = _ref.style;
Object.keys(style).forEach(function (key) {
return container.style[key] = style[key];
});
}
/**
* 容器的正确状态管理和那些容器中的模态。
*/
var ModalManager = function () {
function ModalManager() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref2$hideSiblingNode = _ref2.hideSiblingNodes,
hideSiblingNodes = _ref2$hideSiblingNode === undefined ? true : _ref2$hideSiblingNode,
_ref2$handleContainer = _ref2.handleContainerOverflow,
handleContainerOverflow = _ref2$handleContainer === undefined ? true : _ref2$handleContainer;
_classCallCheck(this, ModalManager);
this.hideSiblingNodes = hideSiblingNodes;
this.handleContainerOverflow = handleContainerOverflow;
this.modals = [];
this.containers = [];
this.data = [];
}
ModalManager.prototype.add = function add(modal, container, className) {
var modalIdx = this.modals.indexOf(modal);
var containerIdx = this.containers.indexOf(container);
if (modalIdx !== -1) {
return modalIdx;
}
modalIdx = this.modals.length;
this.modals.push(modal);
if (this.hideSiblingNodes) {
(0, _manageAriaHidden.hideSiblings)(container, modal.mountNode);
}
if (containerIdx !== -1) {
this.data[containerIdx].modals.push(modal);
return modalIdx;
}
var data = {
modals: [modal],
//right now only the first modal of a container will have its classes applied
classes: className ? className.split(/\s+/) : [],
overflowing: (0, _isOverflowing2["default"])(container)
};
if (this.handleContainerOverflow) {
setContainerStyle(data, container);
}
data.classes.forEach(_class2["default"].addClass.bind(null, container));
this.containers.push(container);
this.data.push(data);
return modalIdx;
};
ModalManager.prototype.remove = function remove(modal) {
var modalIdx = this.modals.indexOf(modal);
if (modalIdx === -1) {
return;
}
var containerIdx = findContainer(this.data, modal);
var data = this.data[containerIdx];
var container = this.containers[containerIdx];
data.modals.splice(data.modals.indexOf(modal), 1);
this.modals.splice(modalIdx, 1);
// if that was the last modal in a container,
// clean up the container
if (data.modals.length === 0) {
data.classes.forEach(_class2["default"].removeClass.bind(null, container));
if (this.handleContainerOverflow) {
removeContainerStyle(data, container);
}
if (this.hideSiblingNodes) {
(0, _manageAriaHidden.showSiblings)(container, modal.mountNode);
}
this.containers.splice(containerIdx, 1);
this.data.splice(containerIdx, 1);
} else if (this.hideSiblingNodes) {
//otherwise make sure the next top modal is visible to a SR
(0, _manageAriaHidden.ariaHidden)(false, data.modals[data.modals.length - 1].mountNode);
}
};
ModalManager.prototype.isTopModal = function isTopModal(modal) {
return !!this.modals.length && this.modals[this.modals.length - 1] === modal;
};
return ModalManager;
}();
exports["default"] = ModalManager;
module.exports = exports['default'];
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = void 0;
var _addClass = _interopRequireDefault(__webpack_require__(89));
exports.addClass = _addClass.default;
var _removeClass = _interopRequireDefault(__webpack_require__(91));
exports.removeClass = _removeClass.default;
var _hasClass = _interopRequireDefault(__webpack_require__(90));
exports.hasClass = _hasClass.default;
var _default = {
addClass: _addClass.default,
removeClass: _removeClass.default,
hasClass: _hasClass.default
};
exports.default = _default;
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = isOverflowing;
var _isWindow = __webpack_require__(120);
var _isWindow2 = _interopRequireDefault(_isWindow);
var _ownerDocument = __webpack_require__(75);
var _ownerDocument2 = _interopRequireDefault(_ownerDocument);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function isBody(node) {
return node && node.tagName.toLowerCase() === 'body';
}
function bodyIsOverflowing(node) {
var doc = (0, _ownerDocument2["default"])(node);
var win = (0, _isWindow2["default"])(doc);
var fullWidth = win.innerWidth;
// Support: ie8, no innerWidth
if (!fullWidth) {
var documentElementRect = doc.documentElement.getBoundingClientRect();
fullWidth = documentElementRect.right - Math.abs(documentElementRect.left);
}
return doc.body.clientWidth < fullWidth;
}
function isOverflowing(container) {
var win = (0, _isWindow2["default"])(container);
return win || isBody(container) ? false : container.scrollHeight > container.clientHeight;
}
module.exports = exports['default'];
/***/ }),
/* 148 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ariaHidden = ariaHidden;
exports.hideSiblings = hideSiblings;
exports.showSiblings = showSiblings;
var BLACKLIST = ['template', 'script', 'style'];
var isHidable = function isHidable(_ref) {
var nodeType = _ref.nodeType,
tagName = _ref.tagName;
return nodeType === 1 && BLACKLIST.indexOf(tagName.toLowerCase()) === -1;
};
var siblings = function siblings(container, mount, cb) {
mount = [].concat(mount);
[].forEach.call(container.children, function (node) {
if (mount.indexOf(node) === -1 && isHidable(node)) {
cb(node);
}
});
};
function ariaHidden(show, node) {
if (!node) {
return;
}
if (show) {
node.setAttribute('aria-hidden', 'true');
} else {
node.removeAttribute('aria-hidden');
}
}
function hideSiblings(container, mountNode) {
siblings(container, mountNode, function (node) {
return ariaHidden(true, node);
});
}
function showSiblings(container, mountNode) {
siblings(container, mountNode, function (node) {
return ariaHidden(false, node);
});
}
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = function (node, event, handler, capture) {
(0, _on2["default"])(node, event, handler, capture);
return {
remove: function remove() {
(0, _off2["default"])(node, event, handler, capture);
}
};
};
var _on = __webpack_require__(16);
var _on2 = _interopRequireDefault(_on);
var _off = __webpack_require__(77);
var _off2 = _interopRequireDefault(_off);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
module.exports = exports['default'];
/***/ }),
/* 150 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = addFocusListener;
/**
* Firefox doesn't have a focusin event so using capture is easiest way to get bubbling
* IE8 can't do addEventListener, but does have onfocusin, so we use that in ie8
*
* We only allow one Listener at a time to avoid stack overflows
*/
function addFocusListener(handler) {
var useFocusin = !document.addEventListener;
var remove = void 0;
if (useFocusin) {
document.attachEvent('onfocusin', handler);
remove = function remove() {
return document.detachEvent('onfocusin', handler);
};
} else {
document.addEventListener('focus', handler, true);
remove = function remove() {
return document.removeEventListener('focus', handler, true);
};
}
return { remove: remove };
}
module.exports = exports['default'];
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = activeElement;
var _ownerDocument = _interopRequireDefault(__webpack_require__(75));
function activeElement(doc) {
if (doc === void 0) {
doc = (0, _ownerDocument.default)();
}
try {
return doc.activeElement;
} catch (e) {
/* ie throws if no active element */
}
}
module.exports = exports["default"];
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
componentClass: _tinperBeeCore.elementType
};
var defaultProps = {
componentClass: 'div',
clsPrefix: 'u-modal-body'
};
var ModalBody = function (_React$Component) {
_inherits(ModalBody, _React$Component);
function ModalBody() {
_classCallCheck(this, ModalBody);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalBody.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
clsPrefix = _props.clsPrefix,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'clsPrefix', 'className']);
var classes = {};
classes['' + clsPrefix] = true;
return _react2["default"].createElement(Component, _extends({}, props, {
className: (0, _classnames2["default"])(className, classes)
}));
};
return ModalBody;
}(_react2["default"].Component);
ModalBody.propTypes = propTypes;
ModalBody.defaultProps = defaultProps;
exports["default"] = ModalBody;
module.exports = exports['default'];
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _beeDnd = __webpack_require__(154);
var _beeDnd2 = _interopRequireDefault(_beeDnd);
var _reResizable = __webpack_require__(259);
var _reResizable2 = _interopRequireDefault(_reResizable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
/**
* 传给dialog的classname
*/
dialogClassName: _propTypes2["default"].string,
contentStyle: _propTypes2["default"].object
};
var defaultProps = {
minHeight: 150,
minWidth: 200,
clsPrefix: 'u-modal'
};
var ModalDialog = function (_React$Component) {
_inherits(ModalDialog, _React$Component);
function ModalDialog() {
var _temp, _this, _ret;
_classCallCheck(this, ModalDialog);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
original: {
x: 0,
y: 0
},
maxWidth: Number.MAX_SAFE_INTEGER,
maxHeight: Number.MAX_SAFE_INTEGER
}, _this.onStart = function () {
var draggable = _this.props.draggable;
return draggable;
}, _this.onStop = function (e, delta) {
_this.setState({
original: {
x: delta.x,
y: delta.y
}
});
}, _this.onResizeStart = function (e, dir, elementRef) {
var onResizeStart = _this.props.onResizeStart;
typeof onResizeStart === "function" && onResizeStart(e, dir, elementRef);
}, _this.onResize = function (e, direction, elementRef, delta) {
var onResize = _this.props.onResize;
var original = _this.state.original;
/* resize 之前的值 */
var originX = original.x;
var originY = original.y;
/* 移动的位移 */
var moveW = delta.width;
var moveH = delta.height;
/* 移动的位移 */
var x = null,
y = null;
/* 处理上边缘 */
if (/left/i.test(direction)) {
x = originX - moveW;
y = originY;
_this.position = { x: x, y: y
/* 处理左边缘 */
};
} else if (/top/i.test(direction)) {
x = originX;
y = originY - moveH;
_this.position = { x: x, y: y };
} else {
_this.position = null;
}
if (x || y) {
elementRef.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
}
if (delta.height) {
_this.updateBodyH();
}
typeof onResize === "function" && onResize(e, direction, elementRef, delta);
}, _this.onResizeStop = function (e, direction, elementRef, delta) {
var onResizeStop = _this.props.onResizeStop;
if (_this.position) {
_this.setState({
original: _this.position
});
}
typeof onResizeStop === "function" && onResizeStop(e, direction, elementRef, delta);
}, _this.updateBodyH = function () {
var $resizable = _reactDom2["default"].findDOMNode(_this.resizable);
var $header = $resizable.querySelector(".u-modal-header");
var $body = $resizable.querySelector(".u-modal-body");
var $footer = $resizable.querySelector(".u-modal-footer");
var totalH = $resizable.style.height;
totalH = Number(totalH.replace("px", ""));
if ($header) {
totalH -= $header.offsetHeight;
}
if ($footer) {
totalH -= $footer.offsetHeight;
}
$body.style.height = totalH + 'px';
}, _this.getMaxSizesFromProps = function () {
var backDropW = _this.backdrop && _this.backdrop.offsetWidth ? _this.backdrop.offsetWidth : Number.MAX_SAFE_INTEGER;
var backDropH = _this.backdrop && _this.backdrop.offsetHeight ? _this.backdrop.offsetHeight : Number.MAX_SAFE_INTEGER;
var maxWidth = typeof _this.props.maxWidth === "undefined" ? backDropW : _this.props.maxWidth;
var maxHeight = typeof _this.props.maxHeight === "undefined" ? backDropH : _this.props.maxHeight;
return { maxWidth: maxWidth, maxHeight: maxHeight };
}, _this.handleWH = function (value) {
var size = value;
if (typeof value === "string" && value.endsWith("px")) {
size = Number(value.replace("px", ""));
} else if (typeof Number(value) === "number" && !Number.isNaN(Number(value))) {
size = Number(value);
}
return size;
}, _temp), _possibleConstructorReturn(_this, _ret);
}
ModalDialog.prototype.componentDidUpdate = function componentDidUpdate() {
if (this.props.resizable) {
var _getMaxSizesFromProps = this.getMaxSizesFromProps(),
maxWidth = _getMaxSizesFromProps.maxWidth,
maxHeight = _getMaxSizesFromProps.maxHeight;
if (maxWidth != this.state.maxWidth) {
this.setState({
maxWidth: maxWidth,
maxHeight: maxHeight
});
}
}
};
/* 开始resize */
/* resizing */
/* resize 结束 */
/**
* 更新Modal.Body的高度
*/
/**
* 获取最大宽度和高度
*/
ModalDialog.prototype.render = function render() {
var _dialogClasses,
_this2 = this;
var _props = this.props,
dialogClassName = _props.dialogClassName,
className = _props.className,
clsPrefix = _props.clsPrefix,
size = _props.size,
style = _props.style,
contentStyle = _props.contentStyle,
children = _props.children,
draggable = _props.draggable,
resizable = _props.resizable,
resizeClassName = _props.resizeClassName,
minHeight = _props.minHeight,
minWidth = _props.minWidth,
props = _objectWithoutProperties(_props, ['dialogClassName', 'className', 'clsPrefix', 'size', 'style', 'contentStyle', 'children', 'draggable', 'resizable', 'resizeClassName', 'minHeight', 'minWidth']);
var _state = this.state,
original = _state.original,
maxWidth = _state.maxWidth,
maxHeight = _state.maxHeight;
var uClassName = _defineProperty({}, '' + clsPrefix, true);
var modalStyle = { display: 'block' };
var dialogClasses = (_dialogClasses = {}, _defineProperty(_dialogClasses, uClassName, false), _defineProperty(_dialogClasses, clsPrefix + '-dialog', true), _dialogClasses);
if (size) {
dialogClasses[clsPrefix + '-' + size] = true;
}
if (draggable) {
dialogClasses[clsPrefix + '-draggable'] = true;
}
return _react2["default"].createElement(
'div',
_extends({}, props, {
tabIndex: '-1',
role: 'dialog',
style: modalStyle,
ref: function ref(_ref3) {
return _this2.backdrop = _ref3;
},
className: (0, _classnames2["default"])(className, uClassName)
}),
_react2["default"].createElement(
'div',
{ className: (0, _classnames2["default"])(dialogClassName, dialogClasses), style: style },
_react2["default"].createElement(
_beeDnd2["default"],
{
handle: '.dnd-handle',
cancel: '.dnd-cancel',
onStart: this.onStart,
onStop: this.onStop,
position: original,
list: []
},
resizable ? _react2["default"].createElement(
_reResizable2["default"],
{
className: resizeClassName,
ref: function ref(c) {
if (c) {
_this2.resizable = c;
}
},
onResizeStart: this.onResizeStart,
onResize: this.onResize,
onResizeStop: this.onResizeStop,
minWidth: this.handleWH(minWidth),
minHeight: this.handleWH(minHeight),
maxWidth: this.handleWH(maxWidth),
maxHeight: this.handleWH(maxHeight)
},
_react2["default"].createElement(
'div',
{ style: _extends({}, contentStyle, { height: "100%" }), className: (0, _classnames2["default"])([clsPrefix + '-content']), role: 'document', ref: function ref(_ref) {
return _this2.resize = _ref;
} },
children
)
) : _react2["default"].createElement(
'div',
{ style: contentStyle, className: (0, _classnames2["default"])([clsPrefix + '-content']), role: 'document', ref: function ref(_ref2) {
return _this2.resize = _ref2;
} },
children
)
)
)
);
};
return ModalDialog;
}(_react2["default"].Component);
ModalDialog.propTypes = propTypes;
ModalDialog.defaultProps = defaultProps;
exports["default"] = ModalDialog;
module.exports = exports['default'];
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Dnd = __webpack_require__(155);
var _Dnd2 = _interopRequireDefault(_Dnd);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Dnd2["default"];
module.exports = exports['default'];
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactBeautifulDnd = __webpack_require__(156);
var _reactDraggable = __webpack_require__(254);
var _reactDraggable2 = _interopRequireDefault(_reactDraggable);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _lodash = __webpack_require__(255);
var _lodash2 = _interopRequireDefault(_lodash);
var _SortList = __webpack_require__(256);
var _SortList2 = _interopRequireDefault(_SortList);
var _Between = __webpack_require__(258);
var _Between2 = _interopRequireDefault(_Between);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
onStart: _propTypes2["default"].func,
onDrag: _propTypes2["default"].func,
onStop: _propTypes2["default"].func,
onDragUpdate: _propTypes2["default"].func,
dropClass: _propTypes2["default"].string,
dropOverClass: _propTypes2["default"].string,
dragClass: _propTypes2["default"].string,
dragingClass: _propTypes2["default"].string,
draggedClass: _propTypes2["default"].string,
className: _propTypes2["default"].string,
style: _propTypes2["default"].object,
list: _propTypes2["default"].array,
otherList: _propTypes2["default"].array,
type: _propTypes2["default"].oneOf(['vertical', 'horizontal', 'betweenVertical', 'betweenHorizontal']),
showKey: _propTypes2["default"].string
};
var defaultProps = {
onStart: function onStart() {},
onDrag: function onDrag() {},
onStop: function onStop() {},
onDragUpdate: function onDragUpdate() {},
list: false,
otherList: [],
dropClass: '',
dropOverClass: '',
dragClass: '',
dragingClass: '',
draggedClass: '',
type: 'vertical'
};
var Dnd = function (_Component) {
_inherits(Dnd, _Component);
function Dnd(props) {
_classCallCheck(this, Dnd);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.state = {
items: _this.props.list || []
};
return _this;
}
Dnd.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (!(0, _lodash2["default"])(this.state.items, nextProps.list)) {
this.setState({
items: nextProps.list
});
}
};
Dnd.prototype.render = function render() {
var _this2 = this;
var self = this;
var DndType = function DndType() {
switch (_this2.props.type) {
case 'vertical':
return _react2["default"].createElement(_SortList2["default"], _this2.props);
break;
case 'horizontal':
return _react2["default"].createElement(_SortList2["default"], _this2.props);
break;
case 'betweenVertical':
return _react2["default"].createElement(_Between2["default"], _this2.props);
break;
case 'betweenHorizontal':
return _react2["default"].createElement(_Between2["default"], _this2.props);
break;
default:
return _react2["default"].createElement(_SortList2["default"], _this2.props);
break;
}
};
return _react2["default"].createElement(
'div',
null,
self.state.items.length ? DndType() : _react2["default"].createElement(
_reactDraggable2["default"],
_extends({ defaultClassName: this.props.dragClass,
defaultClassNameDragging: this.props.dragingClass,
defaultClassNameDragged: this.props.draggedClass
}, this.props),
self.props.children
)
);
};
return Dnd;
}(_react.Component);
Dnd.propTypes = propTypes;
Dnd.defaultProps = defaultProps;
Dnd.Drag = _reactDraggable2["default"];
Dnd.DragDropContext = _reactBeautifulDnd.DragDropContext;
Dnd.Droppable = _reactBeautifulDnd.Droppable;
Dnd.Draggable = _reactBeautifulDnd.Draggable;
exports["default"] = Dnd;
module.exports = exports['default'];
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _extends = _interopDefault(__webpack_require__(157));
var invariant = _interopDefault(__webpack_require__(196));
var cssBoxModel = __webpack_require__(197);
var _Object$keys = _interopDefault(__webpack_require__(198));
var memoizeOne = _interopDefault(__webpack_require__(202));
var redux = __webpack_require__(203);
var _Object$assign = _interopDefault(__webpack_require__(158));
var rafSchd = _interopDefault(__webpack_require__(207));
var _inheritsLoose = _interopDefault(__webpack_require__(208));
var React = __webpack_require__(1);
var React__default = _interopDefault(React);
var PropTypes = _interopDefault(__webpack_require__(6));
var reactRedux = __webpack_require__(215);
var reactMotion = __webpack_require__(240);
var vertical = {
direction: 'vertical',
line: 'y',
crossAxisLine: 'x',
start: 'top',
end: 'bottom',
size: 'height',
crossAxisStart: 'left',
crossAxisEnd: 'right',
crossAxisSize: 'width'
};
var horizontal = {
direction: 'horizontal',
line: 'x',
crossAxisLine: 'y',
start: 'left',
end: 'right',
size: 'width',
crossAxisStart: 'top',
crossAxisEnd: 'bottom',
crossAxisSize: 'height'
};
var origin = {
x: 0,
y: 0
};
var add = function add(point1, point2) {
return {
x: point1.x + point2.x,
y: point1.y + point2.y
};
};
var subtract = function subtract(point1, point2) {
return {
x: point1.x - point2.x,
y: point1.y - point2.y
};
};
var isEqual = function isEqual(point1, point2) {
return point1.x === point2.x && point1.y === point2.y;
};
var negate = function negate(point) {
return {
x: point.x !== 0 ? -point.x : 0,
y: point.y !== 0 ? -point.y : 0
};
};
var absolute = function absolute(point) {
return {
x: Math.abs(point.x),
y: Math.abs(point.y)
};
};
var patch = function patch(line, value, otherValue) {
var _ref;
if (otherValue === void 0) {
otherValue = 0;
}
return _ref = {}, _ref[line] = value, _ref[line === 'x' ? 'y' : 'x'] = otherValue, _ref;
};
var distance = function distance(point1, point2) {
return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
};
var closest = function closest(target, points) {
return Math.min.apply(Math, points.map(function (point) {
return distance(target, point);
}));
};
var apply = function apply(fn) {
return function (point) {
return {
x: fn(point.x),
y: fn(point.y)
};
};
};
var offsetByPosition = function offsetByPosition(spacing, point) {
return {
top: spacing.top + point.y,
left: spacing.left + point.x,
bottom: spacing.bottom + point.y,
right: spacing.right + point.x
};
};
var expandByPosition = function expandByPosition(spacing, position) {
return {
top: spacing.top - position.y,
left: spacing.left - position.x,
right: spacing.right + position.x,
bottom: spacing.bottom + position.y
};
};
var getCorners = function getCorners(spacing) {
return [{
x: spacing.left,
y: spacing.top
}, {
x: spacing.right,
y: spacing.top
}, {
x: spacing.left,
y: spacing.bottom
}, {
x: spacing.right,
y: spacing.bottom
}];
};
var getMaxScroll = (function (_ref) {
var scrollHeight = _ref.scrollHeight,
scrollWidth = _ref.scrollWidth,
height = _ref.height,
width = _ref.width;
var maxScroll = subtract({
x: scrollWidth,
y: scrollHeight
}, {
x: width,
y: height
});
var adjustedMaxScroll = {
x: Math.max(0, maxScroll.x),
y: Math.max(0, maxScroll.y)
};
return adjustedMaxScroll;
});
var clip = function clip(frame, subject) {
var result = cssBoxModel.getRect({
top: Math.max(subject.top, frame.top),
right: Math.min(subject.right, frame.right),
bottom: Math.min(subject.bottom, frame.bottom),
left: Math.max(subject.left, frame.left)
});
if (result.width <= 0 || result.height <= 0) {
return null;
}
return result;
};
var getDroppableDimension = function getDroppableDimension(_ref) {
var descriptor = _ref.descriptor,
isEnabled = _ref.isEnabled,
direction = _ref.direction,
client = _ref.client,
page = _ref.page,
closest$$1 = _ref.closest;
var scrollable = function () {
if (!closest$$1) {
return null;
}
var maxScroll = getMaxScroll({
scrollHeight: closest$$1.scrollHeight,
scrollWidth: closest$$1.scrollWidth,
height: closest$$1.client.paddingBox.height,
width: closest$$1.client.paddingBox.width
});
return {
framePageMarginBox: closest$$1.page.marginBox,
shouldClipSubject: closest$$1.shouldClipSubject,
scroll: {
initial: closest$$1.scroll,
current: closest$$1.scroll,
max: maxScroll,
diff: {
value: origin,
displacement: origin
}
}
};
}();
var subjectPageMarginBox = page.marginBox;
var clippedPageMarginBox = scrollable && scrollable.shouldClipSubject ? clip(scrollable.framePageMarginBox, subjectPageMarginBox) : subjectPageMarginBox;
var viewport = {
closestScrollable: scrollable,
subjectPageMarginBox: subjectPageMarginBox,
clippedPageMarginBox: clippedPageMarginBox
};
var dimension = {
descriptor: descriptor,
axis: direction === 'vertical' ? vertical : horizontal,
isEnabled: isEnabled,
client: client,
page: page,
viewport: viewport
};
return dimension;
};
var scrollDroppable = function scrollDroppable(droppable, newScroll) {
!droppable.viewport.closestScrollable ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
var scrollable = droppable.viewport.closestScrollable;
var framePageMarginBox = scrollable.framePageMarginBox;
var scrollDiff = subtract(newScroll, scrollable.scroll.initial);
var scrollDisplacement = negate(scrollDiff);
var closestScrollable = {
framePageMarginBox: scrollable.framePageMarginBox,
shouldClipSubject: scrollable.shouldClipSubject,
scroll: {
initial: scrollable.scroll.initial,
current: newScroll,
diff: {
value: scrollDiff,
displacement: scrollDisplacement
},
max: scrollable.scroll.max
}
};
var displacedSubject = offsetByPosition(droppable.viewport.subjectPageMarginBox, scrollDisplacement);
var clippedPageMarginBox = closestScrollable.shouldClipSubject ? clip(framePageMarginBox, displacedSubject) : cssBoxModel.getRect(displacedSubject);
var viewport = {
closestScrollable: closestScrollable,
subjectPageMarginBox: droppable.viewport.subjectPageMarginBox,
clippedPageMarginBox: clippedPageMarginBox
};
var result = _extends({}, droppable, {
viewport: viewport
});
return result;
};
var toDroppableMap = memoizeOne(function (droppables) {
return droppables.reduce(function (previous, current) {
previous[current.descriptor.id] = current;
return previous;
}, {});
});
var toDraggableMap = memoizeOne(function (draggables) {
return draggables.reduce(function (previous, current) {
previous[current.descriptor.id] = current;
return previous;
}, {});
});
var toDroppableList = memoizeOne(function (droppables) {
return _Object$keys(droppables).map(function (id) {
return droppables[id];
});
});
var toDraggableList = memoizeOne(function (draggables) {
return _Object$keys(draggables).map(function (id) {
return draggables[id];
});
});
var getDraggablesInsideDroppable = memoizeOne(function (droppable, draggables) {
return toDraggableList(draggables).filter(function (draggable) {
return droppable.descriptor.id === draggable.descriptor.droppableId;
}).sort(function (a, b) {
return a.descriptor.index - b.descriptor.index;
});
});
var isWithin = (function (lowerBound, upperBound) {
return function (value) {
return value <= upperBound && value >= lowerBound;
};
});
var isPositionInFrame = (function (frame) {
var isWithinVertical = isWithin(frame.top, frame.bottom);
var isWithinHorizontal = isWithin(frame.left, frame.right);
return function (point) {
return isWithinVertical(point.y) && isWithinVertical(point.y) && isWithinHorizontal(point.x) && isWithinHorizontal(point.x);
};
});
var getRequiredGrowth = memoizeOne(function (draggable, draggables, droppable) {
var getResult = function getResult(existingSpace) {
var requiredSpace = draggable.page.marginBox[droppable.axis.size];
if (requiredSpace <= existingSpace) {
return null;
}
var requiredGrowth = patch(droppable.axis.line, requiredSpace - existingSpace);
return requiredGrowth;
};
var dimensions = getDraggablesInsideDroppable(droppable, draggables);
if (!dimensions.length) {
var _existingSpace = droppable.page.marginBox[droppable.axis.size];
return getResult(_existingSpace);
}
var endOfDraggables = dimensions[dimensions.length - 1].page.marginBox[droppable.axis.end];
var endOfDroppable = droppable.page.marginBox[droppable.axis.end];
var existingSpace = endOfDroppable - endOfDraggables;
return getResult(existingSpace);
});
var getWithGrowth = memoizeOne(function (area, growth) {
return cssBoxModel.getRect(expandByPosition(area, growth));
});
var getClippedRectWithPlaceholder = function getClippedRectWithPlaceholder(_ref) {
var draggable = _ref.draggable,
draggables = _ref.draggables,
droppable = _ref.droppable,
previousDroppableOverId = _ref.previousDroppableOverId;
var isHome = draggable.descriptor.droppableId === droppable.descriptor.id;
var wasOver = Boolean(previousDroppableOverId && previousDroppableOverId === droppable.descriptor.id);
var clippedPageMarginBox = droppable.viewport.clippedPageMarginBox;
if (!clippedPageMarginBox) {
return clippedPageMarginBox;
}
if (isHome || !wasOver) {
return clippedPageMarginBox;
}
var requiredGrowth = getRequiredGrowth(draggable, draggables, droppable);
if (!requiredGrowth) {
return clippedPageMarginBox;
}
var subjectWithGrowth = getWithGrowth(clippedPageMarginBox, requiredGrowth);
var closestScrollable = droppable.viewport.closestScrollable;
if (!closestScrollable) {
return subjectWithGrowth;
}
if (!closestScrollable.shouldClipSubject) {
return subjectWithGrowth;
}
return clip(closestScrollable.framePageMarginBox, subjectWithGrowth);
};
var getDroppableOver = (function (_ref2) {
var target = _ref2.target,
draggable = _ref2.draggable,
draggables = _ref2.draggables,
droppables = _ref2.droppables,
previousDroppableOverId = _ref2.previousDroppableOverId;
var maybe = toDroppableList(droppables).filter(function (droppable) {
return droppable.isEnabled;
}).find(function (droppable) {
var withPlaceholder = getClippedRectWithPlaceholder({
draggable: draggable,
draggables: draggables,
droppable: droppable,
previousDroppableOverId: previousDroppableOverId
});
if (!withPlaceholder) {
return false;
}
return isPositionInFrame(withPlaceholder)(target);
});
return maybe ? maybe.descriptor.id : null;
});
var noMovement = {
displaced: [],
amount: origin,
isBeyondStartPosition: false
};
var noImpact = {
movement: noMovement,
direction: null,
destination: null
};
var getDisplacementMap = memoizeOne(function (displaced) {
return displaced.reduce(function (map, displacement) {
map[displacement.draggableId] = displacement;
return map;
}, {});
});
var isPartiallyVisibleThroughFrame = (function (frame) {
var isWithinVertical = isWithin(frame.top, frame.bottom);
var isWithinHorizontal = isWithin(frame.left, frame.right);
return function (subject) {
var isContained = isWithinVertical(subject.top) && isWithinVertical(subject.bottom) && isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);
if (isContained) {
return true;
}
var isPartiallyVisibleVertically = isWithinVertical(subject.top) || isWithinVertical(subject.bottom);
var isPartiallyVisibleHorizontally = isWithinHorizontal(subject.left) || isWithinHorizontal(subject.right);
var isPartiallyContained = isPartiallyVisibleVertically && isPartiallyVisibleHorizontally;
if (isPartiallyContained) {
return true;
}
var isBiggerVertically = subject.top < frame.top && subject.bottom > frame.bottom;
var isBiggerHorizontally = subject.left < frame.left && subject.right > frame.right;
var isTargetBiggerThanFrame = isBiggerVertically && isBiggerHorizontally;
if (isTargetBiggerThanFrame) {
return true;
}
var isTargetBiggerOnOneAxis = isBiggerVertically && isPartiallyVisibleHorizontally || isBiggerHorizontally && isPartiallyVisibleVertically;
return isTargetBiggerOnOneAxis;
};
});
var isTotallyVisibleThroughFrame = (function (frame) {
var isWithinVertical = isWithin(frame.top, frame.bottom);
var isWithinHorizontal = isWithin(frame.left, frame.right);
return function (subject) {
var isContained = isWithinVertical(subject.top) && isWithinVertical(subject.bottom) && isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);
return isContained;
};
});
var isVisible = function isVisible(_ref) {
var target = _ref.target,
destination = _ref.destination,
viewport = _ref.viewport,
isVisibleThroughFrameFn = _ref.isVisibleThroughFrameFn;
var displacement = destination.viewport.closestScrollable ? destination.viewport.closestScrollable.scroll.diff.displacement : origin;
var withDisplacement = offsetByPosition(target, displacement);
if (!destination.viewport.clippedPageMarginBox) {
return false;
}
var isVisibleInDroppable = isVisibleThroughFrameFn(destination.viewport.clippedPageMarginBox)(withDisplacement);
var isVisibleInViewport = isVisibleThroughFrameFn(viewport)(withDisplacement);
return isVisibleInDroppable && isVisibleInViewport;
};
var isPartiallyVisible = function isPartiallyVisible(_ref2) {
var target = _ref2.target,
destination = _ref2.destination,
viewport = _ref2.viewport;
return isVisible({
target: target,
destination: destination,
viewport: viewport,
isVisibleThroughFrameFn: isPartiallyVisibleThroughFrame
});
};
var isTotallyVisible = function isTotallyVisible(_ref3) {
var target = _ref3.target,
destination = _ref3.destination,
viewport = _ref3.viewport;
return isVisible({
target: target,
destination: destination,
viewport: viewport,
isVisibleThroughFrameFn: isTotallyVisibleThroughFrame
});
};
var getDisplacement = (function (_ref) {
var draggable = _ref.draggable,
destination = _ref.destination,
previousImpact = _ref.previousImpact,
viewport = _ref.viewport;
var id = draggable.descriptor.id;
var map = getDisplacementMap(previousImpact.movement.displaced);
var isVisible = isPartiallyVisible({
target: draggable.page.marginBox,
destination: destination,
viewport: viewport
});
var shouldAnimate = function () {
if (!isVisible) {
return false;
}
var previous = map[id];
if (!previous) {
return true;
}
return previous.shouldAnimate;
}();
var displacement = {
draggableId: id,
isVisible: isVisible,
shouldAnimate: shouldAnimate
};
return displacement;
});
var withDroppableScroll = (function (droppable, point) {
var closestScrollable = droppable.viewport.closestScrollable;
if (!closestScrollable) {
return point;
}
return add(point, closestScrollable.scroll.diff.value);
});
var inHomeList = (function (_ref) {
var pageBorderBoxCenter = _ref.pageBorderBoxCenter,
draggable = _ref.draggable,
home = _ref.home,
insideHome = _ref.insideHome,
previousImpact = _ref.previousImpact,
viewport = _ref.viewport;
var axis = home.axis;
var originalCenter = draggable.page.borderBox.center;
var currentCenter = withDroppableScroll(home, pageBorderBoxCenter);
var isBeyondStartPosition = currentCenter[axis.line] - originalCenter[axis.line] > 0;
var amount = patch(axis.line, draggable.client.marginBox[axis.size]);
var displaced = insideHome.filter(function (child) {
if (child === draggable) {
return false;
}
var borderBox = child.page.borderBox;
if (isBeyondStartPosition) {
if (borderBox.center[axis.line] < originalCenter[axis.line]) {
return false;
}
return currentCenter[axis.line] > borderBox[axis.start];
}
if (originalCenter[axis.line] < borderBox.center[axis.line]) {
return false;
}
return currentCenter[axis.line] < borderBox[axis.end];
}).map(function (dimension) {
return getDisplacement({
draggable: dimension,
destination: home,
previousImpact: previousImpact,
viewport: viewport.frame
});
});
var ordered = isBeyondStartPosition ? displaced.reverse() : displaced;
var index = function () {
var startIndex = draggable.descriptor.index;
var length = ordered.length;
if (!length) {
return startIndex;
}
if (isBeyondStartPosition) {
return startIndex + length;
}
return startIndex - length;
}();
var movement = {
amount: amount,
displaced: ordered,
isBeyondStartPosition: isBeyondStartPosition
};
var impact = {
movement: movement,
direction: axis.direction,
destination: {
droppableId: home.descriptor.id,
index: index
}
};
return impact;
});
var inForeignList = (function (_ref) {
var pageBorderBoxCenter = _ref.pageBorderBoxCenter,
draggable = _ref.draggable,
destination = _ref.destination,
insideDestination = _ref.insideDestination,
previousImpact = _ref.previousImpact,
viewport = _ref.viewport;
var axis = destination.axis;
var currentCenter = withDroppableScroll(destination, pageBorderBoxCenter);
var displaced = insideDestination.filter(function (child) {
var threshold = child.page.borderBox[axis.end];
return threshold > currentCenter[axis.line];
}).map(function (dimension) {
return getDisplacement({
draggable: dimension,
destination: destination,
previousImpact: previousImpact,
viewport: viewport.frame
});
});
var newIndex = insideDestination.length - displaced.length;
var movement = {
amount: patch(axis.line, draggable.page.marginBox[axis.size]),
displaced: displaced,
isBeyondStartPosition: false
};
var impact = {
movement: movement,
direction: axis.direction,
destination: {
droppableId: destination.descriptor.id,
index: newIndex
}
};
return impact;
});
var getDragImpact = (function (_ref) {
var pageBorderBoxCenter = _ref.pageBorderBoxCenter,
draggable = _ref.draggable,
draggables = _ref.draggables,
droppables = _ref.droppables,
previousImpact = _ref.previousImpact,
viewport = _ref.viewport;
var previousDroppableOverId = previousImpact.destination && previousImpact.destination.droppableId;
var destinationId = getDroppableOver({
target: pageBorderBoxCenter,
draggable: draggable,
draggables: draggables,
droppables: droppables,
previousDroppableOverId: previousDroppableOverId
});
if (!destinationId) {
return noImpact;
}
var destination = droppables[destinationId];
if (!destination.isEnabled) {
return noImpact;
}
var home = droppables[draggable.descriptor.droppableId];
var isWithinHomeDroppable = home.descriptor.id === destinationId;
var insideDestination = getDraggablesInsideDroppable(destination, draggables);
if (isWithinHomeDroppable) {
return inHomeList({
pageBorderBoxCenter: pageBorderBoxCenter,
draggable: draggable,
home: home,
insideHome: insideDestination,
previousImpact: previousImpact || noImpact,
viewport: viewport
});
}
return inForeignList({
pageBorderBoxCenter: pageBorderBoxCenter,
draggable: draggable,
destination: destination,
insideDestination: insideDestination,
previousImpact: previousImpact || noImpact,
viewport: viewport
});
});
var getHomeLocation = (function (critical) {
return {
index: critical.draggable.index,
droppableId: critical.droppable.id
};
});
var getSafeClipped = function getSafeClipped(droppable) {
var rect = droppable.viewport.clippedPageMarginBox;
!rect ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot get clipped area from droppable') : invariant(false) : void 0;
return rect;
};
var getBestCrossAxisDroppable = (function (_ref) {
var isMovingForward = _ref.isMovingForward,
pageBorderBoxCenter = _ref.pageBorderBoxCenter,
source = _ref.source,
droppables = _ref.droppables,
viewport = _ref.viewport;
var sourceClipped = source.viewport.clippedPageMarginBox;
if (!sourceClipped) {
return null;
}
var axis = source.axis;
var isBetweenSourceClipped = isWithin(sourceClipped[axis.start], sourceClipped[axis.end]);
var candidates = toDroppableList(droppables).filter(function (droppable) {
return droppable !== source;
}).filter(function (droppable) {
return droppable.isEnabled;
}).filter(function (droppable) {
var clippedPageMarginBox = droppable.viewport.clippedPageMarginBox;
if (!clippedPageMarginBox) {
return false;
}
return isPartiallyVisibleThroughFrame(viewport.frame)(clippedPageMarginBox);
}).filter(function (droppable) {
var targetClipped = getSafeClipped(droppable);
if (isMovingForward) {
return sourceClipped[axis.crossAxisEnd] < targetClipped[axis.crossAxisEnd];
}
return targetClipped[axis.crossAxisStart] < sourceClipped[axis.crossAxisStart];
}).filter(function (droppable) {
var targetClipped = getSafeClipped(droppable);
var isBetweenDestinationClipped = isWithin(targetClipped[axis.start], targetClipped[axis.end]);
return isBetweenSourceClipped(targetClipped[axis.start]) || isBetweenSourceClipped(targetClipped[axis.end]) || isBetweenDestinationClipped(sourceClipped[axis.start]) || isBetweenDestinationClipped(sourceClipped[axis.end]);
}).sort(function (a, b) {
var first = getSafeClipped(a)[axis.crossAxisStart];
var second = getSafeClipped(b)[axis.crossAxisStart];
if (isMovingForward) {
return first - second;
}
return second - first;
}).filter(function (droppable, index, array) {
return getSafeClipped(droppable)[axis.crossAxisStart] === getSafeClipped(array[0])[axis.crossAxisStart];
});
if (!candidates.length) {
return null;
}
if (candidates.length === 1) {
return candidates[0];
}
var contains = candidates.filter(function (droppable) {
var isWithinDroppable = isWithin(getSafeClipped(droppable)[axis.start], getSafeClipped(droppable)[axis.end]);
return isWithinDroppable(pageBorderBoxCenter[axis.line]);
});
if (contains.length === 1) {
return contains[0];
}
if (contains.length > 1) {
return contains.sort(function (a, b) {
return getSafeClipped(a)[axis.start] - getSafeClipped(b)[axis.start];
})[0];
}
return candidates.sort(function (a, b) {
var first = closest(pageBorderBoxCenter, getCorners(getSafeClipped(a)));
var second = closest(pageBorderBoxCenter, getCorners(getSafeClipped(b)));
if (first !== second) {
return first - second;
}
return getSafeClipped(a)[axis.start] - getSafeClipped(b)[axis.start];
})[0];
});
var withDroppableDisplacement = (function (droppable, point) {
var closestScrollable = droppable.viewport.closestScrollable;
if (!closestScrollable) {
return point;
}
return add(point, closestScrollable.scroll.diff.displacement);
});
var getClosestDraggable = (function (_ref) {
var axis = _ref.axis,
viewport = _ref.viewport,
pageBorderBoxCenter = _ref.pageBorderBoxCenter,
destination = _ref.destination,
insideDestination = _ref.insideDestination;
if (!insideDestination.length) {
return null;
}
var result = insideDestination.filter(function (draggable) {
return isTotallyVisible({
target: draggable.page.borderBox,
destination: destination,
viewport: viewport.frame
});
}).sort(function (a, b) {
var distanceToA = distance(pageBorderBoxCenter, withDroppableDisplacement(destination, a.page.borderBox.center));
var distanceToB = distance(pageBorderBoxCenter, withDroppableDisplacement(destination, b.page.borderBox.center));
if (distanceToA < distanceToB) {
return -1;
}
if (distanceToB < distanceToA) {
return 1;
}
return a.page.borderBox[axis.start] - b.page.borderBox[axis.start];
});
return result.length ? result[0] : null;
});
var moveToEdge = (function (_ref) {
var source = _ref.source,
sourceEdge = _ref.sourceEdge,
destination = _ref.destination,
destinationEdge = _ref.destinationEdge,
destinationAxis = _ref.destinationAxis;
var getCorner = function getCorner(area) {
return patch(destinationAxis.line, area[destinationAxis[destinationEdge]], area[destinationAxis.crossAxisStart]);
};
var corner = getCorner(destination);
var centerDiff = absolute(subtract(source.center, getCorner(source)));
var signed = patch(destinationAxis.line, (sourceEdge === 'end' ? -1 : 1) * centerDiff[destinationAxis.line], centerDiff[destinationAxis.crossAxisLine]);
return add(corner, signed);
});
var toHomeList = (function (_ref) {
var amount = _ref.amount,
homeIndex = _ref.homeIndex,
movingRelativeTo = _ref.movingRelativeTo,
insideDestination = _ref.insideDestination,
draggable = _ref.draggable,
destination = _ref.destination,
previousImpact = _ref.previousImpact,
viewport = _ref.viewport;
var axis = destination.axis;
var targetIndex = insideDestination.indexOf(movingRelativeTo);
!(targetIndex !== -1) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Unable to find target in destination droppable') : invariant(false) : void 0;
if (targetIndex === homeIndex) {
var _newCenter = draggable.page.borderBox.center;
var _newImpact = {
movement: {
displaced: [],
amount: amount,
isBeyondStartPosition: false
},
direction: destination.axis.direction,
destination: {
droppableId: destination.descriptor.id,
index: homeIndex
}
};
return {
pageBorderBoxCenter: withDroppableDisplacement(destination, _newCenter),
impact: _newImpact
};
}
var isMovingPastOriginalIndex = targetIndex > homeIndex;
var edge = isMovingPastOriginalIndex ? 'end' : 'start';
var newCenter = moveToEdge({
source: draggable.page.borderBox,
sourceEdge: edge,
destination: isMovingPastOriginalIndex ? movingRelativeTo.page.borderBox : movingRelativeTo.page.marginBox,
destinationEdge: edge,
destinationAxis: axis
});
var modified = function () {
if (!isMovingPastOriginalIndex) {
return insideDestination.slice(targetIndex, homeIndex);
}
var from = homeIndex + 1;
var to = targetIndex + 1;
return insideDestination.slice(from, to).reverse();
}();
var displaced = modified.map(function (dimension) {
return getDisplacement({
draggable: dimension,
destination: destination,
previousImpact: previousImpact,
viewport: viewport.frame
});
});
var newImpact = {
movement: {
displaced: displaced,
amount: amount,
isBeyondStartPosition: isMovingPastOriginalIndex
},
direction: axis.direction,
destination: {
droppableId: destination.descriptor.id,
index: targetIndex
}
};
return {
pageBorderBoxCenter: withDroppableDisplacement(destination, newCenter),
impact: newImpact
};
});
var toForeignList = (function (_ref) {
var amount = _ref.amount,
pageBorderBoxCenter = _ref.pageBorderBoxCenter,
movingRelativeTo = _ref.movingRelativeTo,
insideDestination = _ref.insideDestination,
draggable = _ref.draggable,
destination = _ref.destination,
previousImpact = _ref.previousImpact,
viewport = _ref.viewport;
var axis = destination.axis;
var isGoingBeforeTarget = Boolean(movingRelativeTo && pageBorderBoxCenter[destination.axis.line] < movingRelativeTo.page.borderBox.center[destination.axis.line]);
if (!movingRelativeTo) {
var _newCenter = moveToEdge({
source: draggable.page.borderBox,
sourceEdge: 'start',
destination: destination.page.contentBox,
destinationEdge: 'start',
destinationAxis: axis
});
var _newImpact = {
movement: {
displaced: [],
amount: amount,
isBeyondStartPosition: false
},
direction: axis.direction,
destination: {
droppableId: destination.descriptor.id,
index: 0
}
};
return {
pageBorderBoxCenter: withDroppableDisplacement(destination, _newCenter),
impact: _newImpact
};
}
var targetIndex = insideDestination.indexOf(movingRelativeTo);
!(targetIndex !== -1) ? process.env.NODE_ENV !== "production" ? invariant(false, 'The target was not found within its droppable') : invariant(false) : void 0;
var proposedIndex = isGoingBeforeTarget ? targetIndex : targetIndex + 1;
var newCenter = moveToEdge({
source: draggable.page.borderBox,
sourceEdge: 'start',
destination: movingRelativeTo.page.marginBox,
destinationEdge: isGoingBeforeTarget ? 'start' : 'end',
destinationAxis: axis
});
var displaced = insideDestination.slice(proposedIndex, insideDestination.length).map(function (dimension) {
return getDisplacement({
draggable: dimension,
destination: destination,
viewport: viewport.frame,
previousImpact: previousImpact
});
});
var newImpact = {
movement: {
displaced: displaced,
amount: amount,
isBeyondStartPosition: false
},
direction: axis.direction,
destination: {
droppableId: destination.descriptor.id,
index: proposedIndex
}
};
return {
pageBorderBoxCenter: withDroppableDisplacement(destination, newCenter),
impact: newImpact
};
});
var moveToNewDroppable = (function (_ref) {
var pageBorderBoxCenter = _ref.pageBorderBoxCenter,
destination = _ref.destination,
insideDestination = _ref.insideDestination,
draggable = _ref.draggable,
movingRelativeTo = _ref.movingRelativeTo,
home = _ref.home,
previousImpact = _ref.previousImpact,
viewport = _ref.viewport;
var amount = patch(destination.axis.line, draggable.client.marginBox[destination.axis.size]);
if (destination.descriptor.id === draggable.descriptor.droppableId) {
!movingRelativeTo ? process.env.NODE_ENV !== "production" ? invariant(false, 'There will always be a target in the original list') : invariant(false) : void 0;
return toHomeList({
amount: amount,
homeIndex: home.index,
movingRelativeTo: movingRelativeTo,
insideDestination: insideDestination,
draggable: draggable,
destination: destination,
previousImpact: previousImpact,
viewport: viewport
});
}
return toForeignList({
amount: amount,
pageBorderBoxCenter: pageBorderBoxCenter,
movingRelativeTo: movingRelativeTo,
insideDestination: insideDestination,
draggable: draggable,
destination: destination,
previousImpact: previousImpact,
viewport: viewport
});
});
var moveCrossAxis = (function (_ref) {
var isMovingForward = _ref.isMovingForward,
pageBorderBoxCenter = _ref.pageBorderBoxCenter,
draggableId = _ref.draggableId,
droppableId = _ref.droppableId,
home = _ref.home,
draggables = _ref.draggables,
droppables = _ref.droppables,
previousImpact = _ref.previousImpact,
viewport = _ref.viewport;
var draggable = draggables[draggableId];
var source = droppables[droppableId];
var destination = getBestCrossAxisDroppable({
isMovingForward: isMovingForward,
pageBorderBoxCenter: pageBorderBoxCenter,
source: source,
droppables: droppables,
viewport: viewport
});
if (!destination) {
return null;
}
var insideDestination = getDraggablesInsideDroppable(destination, draggables);
var movingRelativeTo = getClosestDraggable({
axis: destination.axis,
pageBorderBoxCenter: pageBorderBoxCenter,
destination: destination,
insideDestination: insideDestination,
viewport: viewport
});
if (insideDestination.length && !movingRelativeTo) {
return null;
}
return moveToNewDroppable({
pageBorderBoxCenter: pageBorderBoxCenter,
destination: destination,
draggable: draggable,
movingRelativeTo: movingRelativeTo,
insideDestination: insideDestination,
home: home,
previousImpact: previousImpact || noImpact,
viewport: viewport
});
});
var isTotallyVisibleInNewLocation = (function (_ref) {
var draggable = _ref.draggable,
destination = _ref.destination,
newPageBorderBoxCenter = _ref.newPageBorderBoxCenter,
viewport = _ref.viewport;
var diff = subtract(newPageBorderBoxCenter, draggable.page.borderBox.center);
var shifted = offsetByPosition(draggable.page.borderBox, diff);
return isTotallyVisible({
target: shifted,
destination: destination,
viewport: viewport
});
});
var withFirstAdded = function withFirstAdded(_ref) {
var add = _ref.add,
previousImpact = _ref.previousImpact,
droppable = _ref.droppable,
draggables = _ref.draggables,
viewport = _ref.viewport;
var newDisplacement = {
draggableId: add,
isVisible: true,
shouldAnimate: true
};
var added = [newDisplacement].concat(previousImpact.movement.displaced);
var withUpdatedVisibility = added.map(function (current) {
if (current === newDisplacement) {
return current;
}
var updated = getDisplacement({
draggable: draggables[current.draggableId],
destination: droppable,
previousImpact: previousImpact,
viewport: viewport.frame
});
return updated;
});
return withUpdatedVisibility;
};
var forceVisibleDisplacement = function forceVisibleDisplacement(current) {
if (current.isVisible) {
return current;
}
return {
draggableId: current.draggableId,
isVisible: true,
shouldAnimate: false
};
};
var withFirstRemoved = function withFirstRemoved(_ref2) {
var dragging = _ref2.dragging,
isVisibleInNewLocation = _ref2.isVisibleInNewLocation,
previousImpact = _ref2.previousImpact,
droppable = _ref2.droppable,
draggables = _ref2.draggables;
var last = previousImpact.movement.displaced;
!last.length ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot remove displacement from empty list') : invariant(false) : void 0;
var withFirstRestored = last.slice(1, last.length);
if (!withFirstRestored.length) {
return withFirstRestored;
}
if (isVisibleInNewLocation) {
return withFirstRestored;
}
var axis = droppable.axis;
var sizeOfRestored = draggables[last[0].draggableId].page.marginBox[axis.size];
var sizeOfDragging = draggables[dragging].page.marginBox[axis.size];
var buffer = sizeOfRestored + sizeOfDragging;
var withUpdatedVisibility = withFirstRestored.map(function (displacement, index) {
if (index === 0) {
return forceVisibleDisplacement(displacement);
}
if (buffer > 0) {
var current = draggables[displacement.draggableId];
var size = current.page.marginBox[axis.size];
buffer -= size;
return forceVisibleDisplacement(displacement);
}
return {
draggableId: displacement.draggableId,
isVisible: false,
shouldAnimate: false
};
});
return withUpdatedVisibility;
};
var inHomeList$1 = (function (_ref) {
var isMovingForward = _ref.isMovingForward,
draggableId = _ref.draggableId,
previousPageBorderBoxCenter = _ref.previousPageBorderBoxCenter,
previousImpact = _ref.previousImpact,
droppable = _ref.droppable,
draggables = _ref.draggables,
viewport = _ref.viewport;
var location = previousImpact.destination;
!location ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot move to next index in home list when there is no previous destination') : invariant(false) : void 0;
var draggable = draggables[draggableId];
var axis = droppable.axis;
var insideDroppable = getDraggablesInsideDroppable(droppable, draggables);
var startIndex = draggable.descriptor.index;
var currentIndex = location.index;
var proposedIndex = isMovingForward ? currentIndex + 1 : currentIndex - 1;
if (proposedIndex > insideDroppable.length - 1) {
return null;
}
if (proposedIndex < 0) {
return null;
}
var destination = insideDroppable[proposedIndex];
var isMovingTowardStart = isMovingForward && proposedIndex <= startIndex || !isMovingForward && proposedIndex >= startIndex;
var edge = function () {
if (!isMovingTowardStart) {
return isMovingForward ? 'end' : 'start';
}
return isMovingForward ? 'start' : 'end';
}();
var newPageBorderBoxCenter = moveToEdge({
source: draggable.page.borderBox,
sourceEdge: edge,
destination: destination.page.borderBox,
destinationEdge: edge,
destinationAxis: droppable.axis
});
var isVisibleInNewLocation = isTotallyVisibleInNewLocation({
draggable: draggable,
destination: droppable,
newPageBorderBoxCenter: newPageBorderBoxCenter,
viewport: viewport.frame
});
var displaced = isMovingTowardStart ? withFirstRemoved({
dragging: draggableId,
isVisibleInNewLocation: isVisibleInNewLocation,
previousImpact: previousImpact,
droppable: droppable,
draggables: draggables
}) : withFirstAdded({
add: destination.descriptor.id,
previousImpact: previousImpact,
droppable: droppable,
draggables: draggables,
viewport: viewport
});
var newImpact = {
movement: {
displaced: displaced,
amount: patch(axis.line, draggable.page.marginBox[axis.size]),
isBeyondStartPosition: proposedIndex > startIndex
},
destination: {
droppableId: droppable.descriptor.id,
index: proposedIndex
},
direction: droppable.axis.direction
};
if (isVisibleInNewLocation) {
return {
pageBorderBoxCenter: withDroppableDisplacement(droppable, newPageBorderBoxCenter),
impact: newImpact,
scrollJumpRequest: null
};
}
var distance$$1 = subtract(newPageBorderBoxCenter, previousPageBorderBoxCenter);
var distanceWithScroll = withDroppableDisplacement(droppable, distance$$1);
return {
pageBorderBoxCenter: previousPageBorderBoxCenter,
impact: newImpact,
scrollJumpRequest: distanceWithScroll
};
});
var inForeignList$1 = (function (_ref) {
var isMovingForward = _ref.isMovingForward,
draggableId = _ref.draggableId,
previousImpact = _ref.previousImpact,
previousPageBorderBoxCenter = _ref.previousPageBorderBoxCenter,
droppable = _ref.droppable,
draggables = _ref.draggables,
viewport = _ref.viewport;
!previousImpact.destination ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot move to next index where there is no previous destination') : invariant(false) : void 0;
var location = previousImpact.destination;
var draggable = draggables[draggableId];
var axis = droppable.axis;
var insideForeignDroppable = getDraggablesInsideDroppable(droppable, draggables);
var currentIndex = location.index;
var proposedIndex = isMovingForward ? currentIndex + 1 : currentIndex - 1;
var lastIndex = insideForeignDroppable.length - 1;
if (proposedIndex > insideForeignDroppable.length) {
return null;
}
if (proposedIndex < 0) {
return null;
}
var movingRelativeTo = insideForeignDroppable[Math.min(proposedIndex, lastIndex)];
var isMovingPastLastIndex = proposedIndex > lastIndex;
var sourceEdge = 'start';
var destinationEdge = function () {
if (isMovingPastLastIndex) {
return 'end';
}
return 'start';
}();
var newPageBorderBoxCenter = moveToEdge({
source: draggable.page.borderBox,
sourceEdge: sourceEdge,
destination: movingRelativeTo.page.marginBox,
destinationEdge: destinationEdge,
destinationAxis: droppable.axis
});
var isVisibleInNewLocation = isTotallyVisibleInNewLocation({
draggable: draggable,
destination: droppable,
newPageBorderBoxCenter: newPageBorderBoxCenter,
viewport: viewport.frame
});
var displaced = function () {
if (isMovingForward) {
return withFirstRemoved({
dragging: draggableId,
isVisibleInNewLocation: isVisibleInNewLocation,
previousImpact: previousImpact,
droppable: droppable,
draggables: draggables
});
}
return withFirstAdded({
add: movingRelativeTo.descriptor.id,
previousImpact: previousImpact,
droppable: droppable,
draggables: draggables,
viewport: viewport
});
}();
var newImpact = {
movement: {
displaced: displaced,
amount: patch(axis.line, draggable.page.marginBox[axis.size]),
isBeyondStartPosition: false
},
destination: {
droppableId: droppable.descriptor.id,
index: proposedIndex
},
direction: droppable.axis.direction
};
if (isVisibleInNewLocation) {
return {
pageBorderBoxCenter: withDroppableDisplacement(droppable, newPageBorderBoxCenter),
impact: newImpact,
scrollJumpRequest: null
};
}
var distanceMoving = subtract(newPageBorderBoxCenter, previousPageBorderBoxCenter);
var distanceWithScroll = withDroppableDisplacement(droppable, distanceMoving);
return {
pageBorderBoxCenter: previousPageBorderBoxCenter,
impact: newImpact,
scrollJumpRequest: distanceWithScroll
};
});
var moveToNextIndex = (function (args) {
var draggableId = args.draggableId,
draggables = args.draggables,
droppable = args.droppable;
var draggable = draggables[draggableId];
var isInHomeList = draggable.descriptor.droppableId === droppable.descriptor.id;
if (!droppable.isEnabled) {
return null;
}
if (isInHomeList) {
return inHomeList$1(args);
}
return inForeignList$1(args);
});
var getClientSelection = function getClientSelection(pageBorderBoxCenter, currentScroll) {
return subtract(pageBorderBoxCenter, currentScroll);
};
var moveInDirection = (function (_ref) {
var state = _ref.state,
type = _ref.type;
var _ref2 = function () {
if (state.impact.destination) {
return {
droppable: state.dimensions.droppables[state.impact.destination.droppableId],
isMainAxisMovementAllowed: true
};
}
return {
droppable: state.dimensions.droppables[state.critical.droppable.id],
isMainAxisMovementAllowed: false
};
}(),
droppable = _ref2.droppable,
isMainAxisMovementAllowed = _ref2.isMainAxisMovementAllowed;
var direction = droppable.axis.direction;
var isMovingOnMainAxis = direction === 'vertical' && (type === 'MOVE_UP' || type === 'MOVE_DOWN') || direction === 'horizontal' && (type === 'MOVE_LEFT' || type === 'MOVE_RIGHT');
if (isMovingOnMainAxis && !isMainAxisMovementAllowed) {
return null;
}
var isMovingForward = type === 'MOVE_DOWN' || type === 'MOVE_RIGHT';
if (isMovingOnMainAxis) {
var _result = moveToNextIndex({
isMovingForward: isMovingForward,
draggableId: state.critical.draggable.id,
droppable: droppable,
draggables: state.dimensions.draggables,
previousPageBorderBoxCenter: state.current.page.borderBoxCenter,
previousImpact: state.impact,
viewport: state.viewport
});
if (!_result) {
return null;
}
return {
impact: _result.impact,
clientSelection: getClientSelection(_result.pageBorderBoxCenter, state.viewport.scroll.current),
scrollJumpRequest: _result.scrollJumpRequest
};
}
var home = getHomeLocation(state.critical);
var result = moveCrossAxis({
isMovingForward: isMovingForward,
pageBorderBoxCenter: state.current.page.borderBoxCenter,
draggableId: state.critical.draggable.id,
droppableId: droppable.descriptor.id,
home: home,
draggables: state.dimensions.draggables,
droppables: state.dimensions.droppables,
previousImpact: state.impact,
viewport: state.viewport
});
if (!result) {
return null;
}
return {
clientSelection: getClientSelection(result.pageBorderBoxCenter, state.viewport.scroll.current),
impact: result.impact,
scrollJumpRequest: null
};
});
var scrollViewport = (function (viewport, newScroll) {
var diff = subtract(newScroll, viewport.scroll.initial);
var displacement = negate(diff);
var frame = cssBoxModel.getRect({
top: newScroll.y,
bottom: newScroll.y + viewport.frame.height,
left: newScroll.x,
right: newScroll.x + viewport.frame.width
});
var updated = {
frame: frame,
scroll: {
initial: viewport.scroll.initial,
max: viewport.scroll.max,
current: newScroll,
diff: {
value: diff,
displacement: displacement
}
}
};
return updated;
});
var getHomeImpact = (function (critical, dimensions) {
var home = dimensions.droppables[critical.droppable.id];
var axis = home.axis;
var draggable = dimensions.draggables[critical.draggable.id];
return {
movement: {
displaced: [],
isBeyondStartPosition: false,
amount: patch(axis.line, draggable.client.marginBox[axis.size])
},
direction: axis.direction,
destination: getHomeLocation(critical)
};
});
var getPageItemPositions = (function (client, windowScroll) {
return {
selection: add(client.selection, windowScroll),
borderBoxCenter: add(client.borderBoxCenter, windowScroll),
offset: add(client.offset, windowScroll)
};
});
function isMovementAllowed(state) {
return state.phase === 'DRAGGING' || state.phase === 'COLLECTING';
}
var idle = {
phase: 'IDLE'
};
var preparing = {
phase: 'PREPARING'
};
var moveWithPositionUpdates = function moveWithPositionUpdates(_ref) {
var state = _ref.state,
clientSelection = _ref.clientSelection,
shouldAnimate = _ref.shouldAnimate,
viewport = _ref.viewport,
impact = _ref.impact,
scrollJumpRequest = _ref.scrollJumpRequest;
var newViewport = viewport || state.viewport;
var currentWindowScroll = newViewport.scroll.current;
var client = function () {
var offset = subtract(clientSelection, state.initial.client.selection);
return {
offset: offset,
selection: clientSelection,
borderBoxCenter: add(state.initial.client.borderBoxCenter, offset)
};
}();
var page = getPageItemPositions(client, currentWindowScroll);
var current = {
client: client,
page: page
};
if (state.phase === 'COLLECTING') {
return _extends({
phase: 'COLLECTING'
}, state, {
current: current
});
}
var newImpact = impact || getDragImpact({
pageBorderBoxCenter: page.borderBoxCenter,
draggable: state.dimensions.draggables[state.critical.draggable.id],
draggables: state.dimensions.draggables,
droppables: state.dimensions.droppables,
previousImpact: state.impact,
viewport: newViewport
});
var result = _extends({}, state, {
current: current,
shouldAnimate: shouldAnimate,
impact: newImpact,
scrollJumpRequest: scrollJumpRequest || null,
viewport: newViewport
});
return result;
};
var reducer = (function (state, action) {
if (state === void 0) {
state = idle;
}
if (action.type === 'CLEAN') {
return idle;
}
if (action.type === 'PREPARE') {
return preparing;
}
if (action.type === 'INITIAL_PUBLISH') {
!(state.phase === 'PREPARING') ? process.env.NODE_ENV !== "production" ? invariant(false, 'INITIAL_PUBLISH must come after a PREPARING phase') : invariant(false) : void 0;
var _action$payload = action.payload,
critical = _action$payload.critical,
client = _action$payload.client,
viewport = _action$payload.viewport,
dimensions = _action$payload.dimensions,
autoScrollMode = _action$payload.autoScrollMode;
var initial = {
client: client,
page: {
selection: add(client.selection, viewport.scroll.initial),
borderBoxCenter: add(client.selection, viewport.scroll.initial),
offset: origin
}
};
var result = {
phase: 'DRAGGING',
isDragging: true,
critical: critical,
autoScrollMode: autoScrollMode,
dimensions: dimensions,
initial: initial,
current: initial,
impact: getHomeImpact(critical, dimensions),
viewport: viewport,
scrollJumpRequest: null,
shouldAnimate: false
};
return result;
}
if (action.type === 'COLLECTION_STARTING') {
var _extends2;
if (state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') {
return state;
}
!(state.phase === 'DRAGGING') ? process.env.NODE_ENV !== "production" ? invariant(false, "Collection cannot start from phase " + state.phase) : invariant(false) : void 0;
var _result = _extends({
phase: 'COLLECTING'
}, state, (_extends2 = {}, _extends2["phase"] = 'COLLECTING', _extends2));
return _result;
}
if (action.type === 'PUBLISH') {
!(state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') ? process.env.NODE_ENV !== "production" ? invariant(false, "Unexpected " + action.type + " received in phase " + state.phase) : invariant(false) : void 0;
process.env.NODE_ENV !== "production" ? invariant(false, "Dynamic additions and removals of Draggable and Droppable components\n is currently not supported. But will be soon!") : invariant(false);
}
if (action.type === 'MOVE') {
if (state.phase === 'PREPARING') {
return state;
}
if (state.phase === 'DROP_PENDING') {
return state;
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, action.type + " not permitted in phase " + state.phase) : invariant(false) : void 0;
var _action$payload2 = action.payload,
_client = _action$payload2.client,
shouldAnimate = _action$payload2.shouldAnimate;
if (state.shouldAnimate === shouldAnimate && isEqual(_client, state.current.client.selection)) {
return state;
}
var impact = state.autoScrollMode === 'JUMP' ? state.impact : null;
return moveWithPositionUpdates({
state: state,
clientSelection: _client,
impact: impact,
shouldAnimate: shouldAnimate
});
}
if (action.type === 'UPDATE_DROPPABLE_SCROLL') {
var _extends3, _extends4;
if (state.phase === 'PREPARING') {
return state;
}
if (state.phase === 'DROP_PENDING') {
return state;
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, action.type + " not permitted in phase " + state.phase) : invariant(false) : void 0;
var _action$payload3 = action.payload,
id = _action$payload3.id,
offset = _action$payload3.offset;
var target = state.dimensions.droppables[id];
if (!target) {
return state;
}
var updated = scrollDroppable(target, offset);
var _dimensions = _extends({}, state.dimensions, {
droppables: _extends({}, state.dimensions.droppables, (_extends3 = {}, _extends3[id] = updated, _extends3))
});
var _impact = function () {
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
if (state.autoScrollMode === 'JUMP') {
return state.impact;
}
return getDragImpact({
pageBorderBoxCenter: state.current.page.borderBoxCenter,
draggable: _dimensions.draggables[state.critical.draggable.id],
draggables: _dimensions.draggables,
droppables: _dimensions.droppables,
previousImpact: state.impact,
viewport: state.viewport
});
}();
return _extends({
phase: 'DRAGGING'
}, state, (_extends4 = {}, _extends4["phase"] = state.phase, _extends4.impact = _impact, _extends4.dimensions = _dimensions, _extends4.scrollJumpRequest = null, _extends4));
}
if (action.type === 'UPDATE_DROPPABLE_IS_ENABLED') {
var _extends5, _extends6;
if (state.phase === 'DROP_PENDING') {
return state;
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, "Attempting to move in an unsupported phase " + state.phase) : invariant(false) : void 0;
var _action$payload4 = action.payload,
_id = _action$payload4.id,
isEnabled = _action$payload4.isEnabled;
var _target = state.dimensions.droppables[_id];
!_target ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot find Droppable[id: " + _id + "] to toggle its enabled state") : invariant(false) : void 0;
!(_target.isEnabled !== isEnabled) ? process.env.NODE_ENV !== "production" ? invariant(false, "Trying to set droppable isEnabled to " + String(isEnabled) + "\n but it is already " + String(_target.isEnabled)) : invariant(false) : void 0;
var _updated = _extends({}, _target, {
isEnabled: isEnabled
});
var _dimensions2 = _extends({}, state.dimensions, {
droppables: _extends({}, state.dimensions.droppables, (_extends5 = {}, _extends5[_id] = _updated, _extends5))
});
var _impact2 = getDragImpact({
pageBorderBoxCenter: state.current.page.borderBoxCenter,
draggable: _dimensions2.draggables[state.critical.draggable.id],
draggables: _dimensions2.draggables,
droppables: _dimensions2.droppables,
previousImpact: state.impact,
viewport: state.viewport
});
return _extends({
phase: 'DRAGGING'
}, state, (_extends6 = {}, _extends6["phase"] = state.phase, _extends6.impact = _impact2, _extends6.dimensions = _dimensions2, _extends6));
}
if (action.type === 'MOVE_BY_WINDOW_SCROLL') {
if (state.phase === 'PREPARING') {
return state;
}
if (state.phase === 'DROP_PENDING' || state.phase === 'DROP_ANIMATING') {
return state;
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot move by window in phase " + state.phase) : invariant(false) : void 0;
var newScroll = action.payload.scroll;
if (isEqual(state.viewport.scroll.current, newScroll)) {
return state;
}
var isJumpScrolling = state.autoScrollMode === 'JUMP';
var _impact3 = isJumpScrolling ? state.impact : null;
var _viewport = scrollViewport(state.viewport, newScroll);
return moveWithPositionUpdates({
state: state,
clientSelection: state.current.client.selection,
viewport: _viewport,
shouldAnimate: false,
impact: _impact3
});
}
if (action.type === 'UPDATE_VIEWPORT_MAX_SCROLL') {
var _extends7;
!state.isDragging ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot update the max viewport scroll if not dragging') : invariant(false) : void 0;
var existing = state.viewport;
var _viewport2 = _extends({}, existing, {
scroll: _extends({}, existing.scroll, {
max: action.payload
})
});
return _extends({
phase: 'DRAGGING'
}, state, (_extends7 = {}, _extends7["phase"] = state.phase, _extends7.viewport = _viewport2, _extends7));
}
if (action.type === 'MOVE_UP' || action.type === 'MOVE_DOWN' || action.type === 'MOVE_LEFT' || action.type === 'MOVE_RIGHT') {
if (state.phase === 'PREPARING') {
return state;
}
if (state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') {
return state;
}
!(state.phase === 'DRAGGING') ? process.env.NODE_ENV !== "production" ? invariant(false, action.type + " received while not in DRAGGING phase") : invariant(false) : void 0;
var _result2 = moveInDirection({
state: state,
type: action.type
});
if (!_result2) {
return state;
}
return moveWithPositionUpdates({
state: state,
impact: _result2.impact,
clientSelection: _result2.clientSelection,
shouldAnimate: true,
scrollJumpRequest: _result2.scrollJumpRequest
});
}
if (action.type === 'DROP_PENDING') {
var _extends8;
var reason = action.payload.reason;
!(state.phase === 'COLLECTING') ? process.env.NODE_ENV !== "production" ? invariant(false, 'Can only move into the DROP_PENDING phase from the COLLECTING phase') : invariant(false) : void 0;
var newState = _extends({
phase: 'DROP_PENDING'
}, state, (_extends8 = {}, _extends8["phase"] = 'DROP_PENDING', _extends8.isWaiting = true, _extends8.reason = reason, _extends8));
return newState;
}
if (action.type === 'DROP_ANIMATE') {
var pending = action.payload;
!(state.phase === 'DRAGGING' || state.phase === 'DROP_PENDING') ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot animate drop from phase " + state.phase) : invariant(false) : void 0;
var _result3 = {
phase: 'DROP_ANIMATING',
pending: pending,
dimensions: state.dimensions
};
return _result3;
}
if (action.type === 'DROP_COMPLETE') {
return idle;
}
return state;
});
var lift = function lift(args) {
return {
type: 'LIFT',
payload: args
};
};
var initialPublish = function initialPublish(args) {
return {
type: 'INITIAL_PUBLISH',
payload: args
};
};
var publish = function publish(args) {
return {
type: 'PUBLISH',
payload: args
};
};
var collectionStarting = function collectionStarting() {
return {
type: 'COLLECTION_STARTING',
payload: null
};
};
var updateDroppableScroll = function updateDroppableScroll(args) {
return {
type: 'UPDATE_DROPPABLE_SCROLL',
payload: args
};
};
var updateDroppableIsEnabled = function updateDroppableIsEnabled(args) {
return {
type: 'UPDATE_DROPPABLE_IS_ENABLED',
payload: args
};
};
var move = function move(args) {
return {
type: 'MOVE',
payload: args
};
};
var moveByWindowScroll = function moveByWindowScroll(args) {
return {
type: 'MOVE_BY_WINDOW_SCROLL',
payload: args
};
};
var updateViewportMaxScroll = function updateViewportMaxScroll(max) {
return {
type: 'UPDATE_VIEWPORT_MAX_SCROLL',
payload: max
};
};
var moveUp = function moveUp() {
return {
type: 'MOVE_UP',
payload: null
};
};
var moveDown = function moveDown() {
return {
type: 'MOVE_DOWN',
payload: null
};
};
var moveRight = function moveRight() {
return {
type: 'MOVE_RIGHT',
payload: null
};
};
var moveLeft = function moveLeft() {
return {
type: 'MOVE_LEFT',
payload: null
};
};
var clean = function clean() {
return {
type: 'CLEAN',
payload: null
};
};
var prepare = function prepare() {
return {
type: 'PREPARE',
payload: null
};
};
var animateDrop = function animateDrop(pending) {
return {
type: 'DROP_ANIMATE',
payload: pending
};
};
var completeDrop = function completeDrop(result) {
return {
type: 'DROP_COMPLETE',
payload: result
};
};
var drop = function drop(args) {
return {
type: 'DROP',
payload: args
};
};
var dropPending = function dropPending(args) {
return {
type: 'DROP_PENDING',
payload: args
};
};
var dropAnimationFinished = function dropAnimationFinished() {
return {
type: 'DROP_ANIMATION_FINISHED',
payload: null
};
};
var lift$1 = (function (getMarshal) {
var timeoutId = null;
var tryAbortCriticalCollection = function tryAbortCriticalCollection() {
if (timeoutId == null) {
return;
}
clearTimeout(timeoutId);
timeoutId = null;
};
return function (_ref) {
var getState = _ref.getState,
dispatch = _ref.dispatch;
return function (next) {
return function (action) {
if (action.type === 'CLEAN') {
tryAbortCriticalCollection();
next(action);
return;
}
if (action.type !== 'LIFT') {
next(action);
return;
}
!!timeoutId ? process.env.NODE_ENV !== "production" ? invariant(false, 'There should not be a pending complete lift phase when a lift action is fired') : invariant(false) : void 0;
var marshal = getMarshal();
var _action$payload = action.payload,
id = _action$payload.id,
client = _action$payload.client,
autoScrollMode = _action$payload.autoScrollMode,
viewport = _action$payload.viewport;
var initial = getState();
if (initial.phase === 'DROP_ANIMATING') {
dispatch(completeDrop(initial.pending.result));
}
var postFlushState = getState();
!(postFlushState.phase === 'IDLE') ? process.env.NODE_ENV !== "production" ? invariant(false, 'Incorrect phase to start a drag') : invariant(false) : void 0;
dispatch(prepare());
timeoutId = setTimeout(function () {
timeoutId = null;
var state = getState();
!(state.phase === 'PREPARING') ? process.env.NODE_ENV !== "production" ? invariant(false, 'Invalid phase for completing lift') : invariant(false) : void 0;
var scrollOptions = {
shouldPublishImmediately: autoScrollMode === 'JUMP'
};
var request = {
draggableId: id,
scrollOptions: scrollOptions
};
var _marshal$startPublish = marshal.startPublishing(request, viewport.scroll.current),
critical = _marshal$startPublish.critical,
dimensions = _marshal$startPublish.dimensions;
dispatch(initialPublish({
critical: critical,
dimensions: dimensions,
client: client,
autoScrollMode: autoScrollMode,
viewport: viewport
}));
});
};
};
};
});
var style = (function (marshal) {
return function () {
return function (next) {
return function (action) {
if (action.type === 'INITIAL_PUBLISH') {
marshal.dragging();
}
if (action.type === 'COLLECTION_STARTING') {
marshal.collecting();
}
if (action.type === 'PUBLISH') {
marshal.dragging();
}
if (action.type === 'DROP_ANIMATE') {
marshal.dropping(action.payload.result.reason);
}
if (action.type === 'CLEAN' || action.type === 'DROP_COMPLETE') {
marshal.resting();
}
next(action);
};
};
};
});
var getNewHomeClientBorderBoxCenter = (function (_ref) {
var movement = _ref.movement,
draggable = _ref.draggable,
draggables = _ref.draggables,
destination = _ref.destination;
var originalCenter = draggable.client.borderBox.center;
if (destination == null) {
return originalCenter;
}
var displaced = movement.displaced,
isBeyondStartPosition = movement.isBeyondStartPosition;
var axis = destination.axis;
var isWithinHomeDroppable = destination.descriptor.id === draggable.descriptor.droppableId;
if (isWithinHomeDroppable && !displaced.length) {
return originalCenter;
}
var draggablesInDestination = getDraggablesInsideDroppable(destination, draggables);
var movingRelativeTo = function () {
if (isWithinHomeDroppable) {
return draggables[displaced[0].draggableId].client.borderBox;
}
if (displaced.length) {
return draggables[displaced[0].draggableId].client.borderBox;
}
if (draggablesInDestination.length) {
return draggablesInDestination[draggablesInDestination.length - 1].client.marginBox;
}
return destination.client.contentBox;
}();
var _ref2 = function () {
if (isWithinHomeDroppable) {
if (isBeyondStartPosition) {
return {
sourceEdge: 'end',
destinationEdge: 'end'
};
}
return {
sourceEdge: 'start',
destinationEdge: 'start'
};
}
if (!displaced.length && draggablesInDestination.length) {
return {
sourceEdge: 'start',
destinationEdge: 'end'
};
}
return {
sourceEdge: 'start',
destinationEdge: 'start'
};
}(),
sourceEdge = _ref2.sourceEdge,
destinationEdge = _ref2.destinationEdge;
var source = draggable.client.borderBox;
var targetCenter = moveToEdge({
source: source,
sourceEdge: sourceEdge,
destination: movingRelativeTo,
destinationEdge: destinationEdge,
destinationAxis: axis
});
return targetCenter;
});
var getScrollDisplacement = function getScrollDisplacement(droppable, viewport) {
return withDroppableDisplacement(droppable, viewport.scroll.diff.displacement);
};
var drop$1 = (function (_ref) {
var getState = _ref.getState,
dispatch = _ref.dispatch;
return function (next) {
return function (action) {
if (action.type !== 'DROP') {
next(action);
return;
}
var state = getState();
var reason = action.payload.reason;
if (state.phase === 'COLLECTING') {
dispatch(dropPending({
reason: reason
}));
return;
}
if (state.phase === 'PREPARING') {
dispatch(clean());
return;
}
if (state.phase === 'IDLE') {
return;
}
var isWaitingForDrop = state.phase === 'DROP_PENDING' && state.isWaiting;
!!isWaitingForDrop ? process.env.NODE_ENV !== "production" ? invariant(false, 'A DROP action occurred while DROP_PENDING and still waiting') : invariant(false) : void 0;
!(state.phase === 'DRAGGING' || state.phase === 'DROP_PENDING') ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot drop in phase: " + state.phase) : invariant(false) : void 0;
var critical = state.critical;
var dimensions = state.dimensions;
var impact = reason === 'DROP' ? state.impact : noImpact;
var home = dimensions.droppables[state.critical.droppable.id];
var draggable = dimensions.draggables[state.critical.draggable.id];
var droppable = impact && impact.destination ? dimensions.droppables[impact.destination.droppableId] : null;
var source = {
index: critical.draggable.index,
droppableId: critical.droppable.id
};
var destination = reason === 'DROP' ? impact.destination : null;
var result = {
draggableId: draggable.descriptor.id,
type: home.descriptor.type,
source: source,
destination: destination,
reason: reason
};
var clientOffset = function () {
if (reason === 'CANCEL') {
return origin;
}
var newBorderBoxClientCenter = getNewHomeClientBorderBoxCenter({
movement: impact.movement,
draggable: draggable,
draggables: dimensions.draggables,
destination: droppable
});
return subtract(newBorderBoxClientCenter, draggable.client.borderBox.center);
}();
var newHomeOffset = add(clientOffset, getScrollDisplacement(droppable || home, state.viewport));
var isAnimationRequired = !isEqual(state.current.client.offset, newHomeOffset);
var pending = {
newHomeOffset: newHomeOffset,
result: result,
impact: impact
};
if (isAnimationRequired) {
dispatch(animateDrop(pending));
return;
}
dispatch(completeDrop(result));
};
};
});
var onDragStart = function onDragStart(start) {
return "\n You have lifted an item in position " + (start.source.index + 1) + ".\n Use the arrow keys to move, space bar to drop, and escape to cancel.\n";
};
var onDragUpdate = function onDragUpdate(update) {
if (!update.destination) {
return 'You are currently not dragging over a droppable area';
}
if (update.source.droppableId === update.destination.droppableId) {
return "You have moved the item to position " + (update.destination.index + 1);
}
return "\n You have moved the item from list " + update.source.droppableId + " in position " + (update.source.index + 1) + "\n to list " + update.destination.droppableId + " in position " + (update.destination.index + 1) + "\n ";
};
var onDragEnd = function onDragEnd(result) {
if (result.reason === 'CANCEL') {
return "\n Movement cancelled.\n The item has returned to its starting position of " + (result.source.index + 1) + "\n ";
}
if (!result.destination) {
return "\n The item has been dropped while not over a droppable location.\n The item has returned to its starting position of " + (result.source.index + 1) + "\n ";
}
if (result.source.droppableId === result.destination.droppableId) {
if (result.source.index === result.destination.index) {
return "\n You have dropped the item.\n It has been dropped on its starting position of " + (result.source.index + 1) + "\n ";
}
return "\n You have dropped the item.\n It has moved from position " + (result.source.index + 1) + " to " + (result.destination.index + 1) + "\n ";
}
return "\n You have dropped the item.\n It has moved from position " + (result.source.index + 1) + " in list " + result.source.droppableId + "\n to position " + (result.destination.index + 1) + " in list " + result.destination.droppableId + "\n ";
};
var preset = {
onDragStart: onDragStart,
onDragUpdate: onDragUpdate,
onDragEnd: onDragEnd
};
var records = {};
var flag = '__react-beautiful-dnd-debug-timings-hook__';
var isTimingsEnabled = function isTimingsEnabled() {
return Boolean(window[flag]);
};
var start = function start(key) {
if (process.env.NODE_ENV !== 'production') {
if (!isTimingsEnabled()) {
return;
}
var now = performance.now();
records[key] = now;
}
};
var finish = function finish(key) {
if (process.env.NODE_ENV !== 'production') {
if (!isTimingsEnabled()) {
return;
}
var now = performance.now();
var previous = records[key];
!previous ? process.env.NODE_ENV !== "production" ? invariant(false, 'cannot finish timing as no previous time found') : invariant(false) : void 0;
var result = now - previous;
var rounded = result.toFixed(2);
var style = function () {
if (result < 12) {
return {
textColor: 'green',
symbol: '✅'
};
}
if (result < 40) {
return {
textColor: 'orange',
symbol: '⚠️'
};
}
return {
textColor: 'red',
symbol: '❌'
};
}();
console.log(style.symbol + " %cTiming %c" + rounded + " %cms %c" + key, 'color: blue; font-weight: bold; ', "color: " + style.textColor + "; font-size: 1.1em;", 'color: grey;', 'color: purple; font-weight: bold;');
}
};
var withTimings = function withTimings(key, fn) {
start(key);
fn();
finish(key);
};
var areLocationsEqual = function areLocationsEqual(first, second) {
if (first == null && second == null) {
return true;
}
if (first == null || second == null) {
return false;
}
return first.droppableId === second.droppableId && first.index === second.index;
};
var isCriticalEqual = function isCriticalEqual(first, second) {
if (first === second) {
return true;
}
var isDraggableEqual = first.draggable.id === second.draggable.id && first.draggable.droppableId === second.draggable.droppableId && first.draggable.type === second.draggable.type && first.draggable.index === second.draggable.index;
var isDroppableEqual = first.droppable.id === second.droppable.id && first.droppable.type === second.droppable.type;
return isDraggableEqual && isDroppableEqual;
};
var getExpiringAnnounce = function getExpiringAnnounce(announce) {
var wasCalled = false;
var isExpired = false;
setTimeout(function () {
isExpired = true;
});
var result = function result(message) {
if (wasCalled) {
if (process.env.NODE_ENV !== 'production') {
console.warn('Announcement already made. Not making a second announcement');
}
return;
}
if (isExpired) {
if (process.env.NODE_ENV !== 'production') {
console.warn("\n Announcements cannot be made asynchronously.\n Default message has already been announced.\n ");
}
return;
}
wasCalled = true;
announce(message);
};
result.wasCalled = function () {
return wasCalled;
};
return result;
};
var getDragStart = function getDragStart(critical) {
return {
draggableId: critical.draggable.id,
type: critical.droppable.type,
source: {
droppableId: critical.droppable.id,
index: critical.draggable.index
}
};
};
var hooks = (function (getHooks, announce) {
var execute = function execute(hook, data, getDefaultMessage) {
if (!hook) {
announce(getDefaultMessage(data));
return;
}
var willExpire = getExpiringAnnounce(announce);
var provided = {
announce: willExpire
};
hook(data, provided);
if (!willExpire.wasCalled()) {
announce(getDefaultMessage(data));
}
};
var publisher = function () {
var lastLocation = null;
var lastCritical = null;
var _isDragStartPublished = false;
var beforeStart = function beforeStart(critical) {
!!_isDragStartPublished ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot fire onBeforeDragStart as a drag start has already been published') : invariant(false) : void 0;
withTimings('onBeforeDragStart', function () {
var fn = getHooks().onBeforeDragStart;
if (fn) {
fn(getDragStart(critical));
}
});
};
var start$$1 = function start$$1(critical) {
!!_isDragStartPublished ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot fire onBeforeDragStart as a drag start has already been published') : invariant(false) : void 0;
var data = getDragStart(critical);
lastCritical = critical;
lastLocation = data.source;
_isDragStartPublished = true;
withTimings('onDragStart', function () {
return execute(getHooks().onDragStart, data, preset.onDragStart);
});
};
var move = function move(critical, location) {
!(_isDragStartPublished && lastCritical) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot fire onDragMove when onDragStart has not been called') : invariant(false) : void 0;
var hasCriticalChanged = !isCriticalEqual(critical, lastCritical);
if (hasCriticalChanged) {
lastCritical = critical;
}
var hasLocationChanged = !areLocationsEqual(lastLocation, location);
if (hasLocationChanged) {
lastLocation = location;
}
if (!hasCriticalChanged && !hasLocationChanged) {
return;
}
var data = _extends({}, getDragStart(critical), {
destination: location
});
withTimings('onDragUpdate', function () {
return execute(getHooks().onDragUpdate, data, preset.onDragUpdate);
});
};
var drop = function drop(result) {
!_isDragStartPublished ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot fire onDragEnd when there is no matching onDragStart') : invariant(false) : void 0;
_isDragStartPublished = false;
lastLocation = null;
lastCritical = null;
withTimings('onDragEnd', function () {
return execute(getHooks().onDragEnd, result, preset.onDragEnd);
});
};
var abort = function abort() {
!(_isDragStartPublished && lastCritical) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot cancel when onDragStart not fired') : invariant(false) : void 0;
var result = _extends({}, getDragStart(lastCritical), {
destination: null,
reason: 'CANCEL'
});
drop(result);
};
return {
beforeStart: beforeStart,
start: start$$1,
move: move,
drop: drop,
abort: abort,
isDragStartPublished: function isDragStartPublished() {
return _isDragStartPublished;
}
};
}();
return function (store) {
return function (next) {
return function (action) {
if (action.type === 'INITIAL_PUBLISH') {
var critical = action.payload.critical;
publisher.beforeStart(critical);
next(action);
publisher.start(critical);
return;
}
next(action);
if (action.type === 'DROP_COMPLETE') {
var result = action.payload;
publisher.drop(result);
return;
}
if (action.type === 'CLEAN') {
if (publisher.isDragStartPublished()) {
publisher.abort();
}
return;
}
if (!publisher.isDragStartPublished()) {
return;
}
var state = store.getState();
if (state.phase === 'DRAGGING') {
publisher.move(state.critical, state.impact.destination);
}
};
};
};
});
var dropAnimationFinish = (function (store) {
return function (next) {
return function (action) {
if (action.type !== 'DROP_ANIMATION_FINISHED') {
next(action);
return;
}
var state = store.getState();
!(state.phase === 'DROP_ANIMATING') ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot finish a drop animating when no drop is occurring') : invariant(false) : void 0;
store.dispatch(completeDrop(state.pending.result));
};
};
});
var dimensionMarshalStopper = (function (getMarshal) {
return function () {
return function (next) {
return function (action) {
if (action.type === 'DROP_COMPLETE' || action.type === 'CLEAN' || action.type === 'DROP_ANIMATE') {
var marshal = getMarshal();
marshal.stopPublishing();
}
next(action);
};
};
};
});
var shouldCancel = function shouldCancel(action) {
return action.type === 'CANCEL' || action.type === 'DROP_ANIMATE' || action.type === 'DROP' || action.type === 'DROP_COMPLETE' || action.type === 'COLLECTION_STARTING';
};
var autoScroll = (function (getScroller) {
return function (store) {
return function (next) {
return function (action) {
if (shouldCancel(action)) {
getScroller().cancel();
next(action);
return;
}
next(action);
var state = store.getState();
if (state.phase !== 'DRAGGING') {
return;
}
if (state.autoScrollMode === 'FLUID') {
getScroller().fluidScroll(state);
return;
}
if (!state.scrollJumpRequest) {
return;
}
getScroller().jumpScroll(state);
};
};
};
});
var shouldCheckOnAction = function shouldCheckOnAction(action) {
return action.type === 'MOVE' || action.type === 'MOVE_UP' || action.type === 'MOVE_RIGHT' || action.type === 'MOVE_DOWN' || action.type === 'MOVE_LEFT' || action.type === 'MOVE_BY_WINDOW_SCROLL';
};
var hasDroppableOverChanged = function hasDroppableOverChanged(previous, current) {
if (!previous) {
return Boolean(current);
}
if (!current) {
return Boolean(previous);
}
return previous.droppableId !== current.droppableId;
};
var getNewMaxScroll = function getNewMaxScroll(previous, current, action) {
if (!shouldCheckOnAction(action)) {
return null;
}
if (!isMovementAllowed(previous) || !isMovementAllowed(current)) {
return null;
}
if (!hasDroppableOverChanged(previous.impact.destination, current.impact.destination)) {
return null;
}
var viewport = current.viewport;
var doc = document.documentElement;
!doc ? process.env.NODE_ENV !== "production" ? invariant(false, 'Could not find document.documentElement') : invariant(false) : void 0;
var maxScroll = getMaxScroll({
scrollHeight: doc.scrollHeight,
scrollWidth: doc.scrollWidth,
width: viewport.frame.width,
height: viewport.frame.height
});
if (isEqual(maxScroll, viewport.scroll.max)) {
return null;
}
return maxScroll;
};
var maxScrollUpdater = (function (store) {
return function (next) {
return function (action) {
var previous = store.getState();
next(action);
var current = store.getState();
var maxScroll = getNewMaxScroll(previous, current, action);
if (maxScroll) {
next(updateViewportMaxScroll(maxScroll));
}
};
};
});
var composeEnhancers = typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : redux.compose;
var createStore = (function (_ref) {
var getDimensionMarshal = _ref.getDimensionMarshal,
styleMarshal = _ref.styleMarshal,
getHooks = _ref.getHooks,
announce = _ref.announce,
getScroller = _ref.getScroller;
return redux.createStore(reducer, composeEnhancers(redux.applyMiddleware(style(styleMarshal), dimensionMarshalStopper(getDimensionMarshal), lift$1(getDimensionMarshal), drop$1, dropAnimationFinish, maxScrollUpdater, autoScroll(getScroller), hooks(getHooks, announce))));
});
var getEmptyMap = function getEmptyMap() {
return {
draggables: {},
droppables: {}
};
};
var timingKey = 'Publish collection from DOM';
var createPublisher = (function (_ref) {
var getProvided = _ref.getProvided,
callbacks = _ref.callbacks;
var advancedUsageWarning = function () {
if (process.env.NODE_ENV === 'production') {
return function () {};
}
var hasAnnounced = false;
return function () {
if (hasAnnounced) {
return;
}
hasAnnounced = true;
if (process.env.NODE_ENV === 'production') {
return;
}
console.warn("\n Advanced usage warning: you are adding or removing a dimension during a drag\n This an advanced feature used to support dynamic interactions such as lazy loading lists.\n\n Keep in mind the following restrictions:\n\n - Draggable's can only be added to Droppable's that are scroll containers\n - Adding a Droppable cannot impact the placement of other Droppables\n (it cannot push a Droppable on the page)\n\n (This warning will be stripped in production builds)\n ".trim());
};
}();
var additions = getEmptyMap();
var removals = getEmptyMap();
var frameId = null;
var reset = function reset() {
additions = getEmptyMap();
removals = getEmptyMap();
};
var collect = function collect() {
advancedUsageWarning();
if (frameId) {
return;
}
frameId = requestAnimationFrame(function () {
frameId = null;
callbacks.collectionStarting();
start(timingKey);
var _getProvided = getProvided(),
entries = _getProvided.entries,
collection = _getProvided.collection;
var windowScroll = collection.initialWindowScroll;
var draggables = _Object$keys(additions.draggables).map(function (id) {
return entries.draggables[id].getDimension(windowScroll);
});
var droppables = _Object$keys(additions.droppables).map(function (id) {
return entries.droppables[id].callbacks.getDimensionAndWatchScroll(windowScroll, collection.scrollOptions);
});
var result = {
additions: {
draggables: draggables,
droppables: droppables
},
removals: {
draggables: _Object$keys(removals.draggables),
droppables: _Object$keys(removals.droppables)
}
};
reset();
finish(timingKey);
callbacks.publish(result);
});
};
var addDraggable = function addDraggable(id) {
additions.draggables[id] = true;
if (removals.draggables[id]) {
delete removals.draggables[id];
}
collect();
};
var removeDraggable = function removeDraggable(id) {
removals.draggables[id] = true;
if (additions.draggables[id]) {
delete additions.draggables[id];
}
collect();
};
var addDroppable = function addDroppable(id) {
additions.droppables[id] = true;
if (removals.droppables[id]) {
delete removals.droppables[id];
}
collect();
};
var removeDroppable = function removeDroppable(id) {
removals.droppables[id] = true;
if (additions.droppables[id]) {
delete additions.droppables[id];
}
collect();
};
var stop = function stop() {
if (!frameId) {
return;
}
cancelAnimationFrame(frameId);
frameId = null;
reset();
};
return {
addDraggable: addDraggable,
removeDraggable: removeDraggable,
addDroppable: addDroppable,
removeDroppable: removeDroppable,
stop: stop
};
});
var createDimensionMarshal = (function (callbacks) {
var entries = {
droppables: {},
draggables: {}
};
var collection = null;
var publisher = createPublisher({
callbacks: {
publish: callbacks.publish,
collectionStarting: callbacks.collectionStarting
},
getProvided: function getProvided() {
!collection ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot get scroll options when there is no collection') : invariant(false) : void 0;
return {
entries: entries,
collection: collection
};
}
});
var registerDraggable = function registerDraggable(descriptor, getDimension) {
var entry = {
descriptor: descriptor,
getDimension: getDimension
};
entries.draggables[descriptor.id] = entry;
if (!collection) {
return;
}
if (collection.critical.draggable.type !== descriptor.type) {
return;
}
publisher.addDraggable(descriptor.id);
};
var updateDraggable = function updateDraggable(previous, descriptor, getDimension) {
!entries.draggables[previous.id] ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot update draggable registration as no previous registration was found') : invariant(false) : void 0;
delete entries.draggables[previous.id];
var entry = {
descriptor: descriptor,
getDimension: getDimension
};
entries.draggables[descriptor.id] = entry;
};
var unregisterDraggable = function unregisterDraggable(descriptor) {
var entry = entries.draggables[descriptor.id];
!entry ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot unregister Draggable with id " + descriptor.id + " as it is not registered") : invariant(false) : void 0;
if (entry.descriptor !== descriptor) {
return;
}
delete entries.draggables[descriptor.id];
if (!collection) {
return;
}
!(collection.critical.draggable.id !== descriptor.id) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot remove the dragging item during a drag') : invariant(false) : void 0;
if (descriptor.type !== collection.critical.draggable.type) {
return;
}
publisher.removeDraggable(descriptor.id);
};
var registerDroppable = function registerDroppable(descriptor, droppableCallbacks) {
var id = descriptor.id;
entries.droppables[id] = {
descriptor: descriptor,
callbacks: droppableCallbacks
};
if (!collection) {
return;
}
if (descriptor.type !== collection.critical.droppable.type) {
return;
}
publisher.addDroppable(id);
};
var updateDroppable = function updateDroppable(previous, descriptor, droppableCallbacks) {
!entries.droppables[previous.id] ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot update droppable registration as no previous registration was found') : invariant(false) : void 0;
delete entries.droppables[previous.id];
var entry = {
descriptor: descriptor,
callbacks: droppableCallbacks
};
entries.droppables[descriptor.id] = entry;
if (collection) {
process.env.NODE_ENV !== "production" ? invariant(false, 'You are not able to update the id or type of a droppable during a drag') : invariant(false);
}
};
var unregisterDroppable = function unregisterDroppable(descriptor) {
var entry = entries.droppables[descriptor.id];
!entry ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot unregister Droppable with id " + descriptor.id + " as as it is not registered") : invariant(false) : void 0;
if (entry.descriptor !== descriptor) {
return;
}
delete entries.droppables[descriptor.id];
if (!collection) {
return;
}
!(collection.critical.droppable.id !== descriptor.id) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot remove the home Droppable during a drag') : invariant(false) : void 0;
if (collection.critical.droppable.type !== descriptor.type) {
return;
}
publisher.removeDroppable(descriptor.id);
};
var updateDroppableIsEnabled = function updateDroppableIsEnabled(id, isEnabled) {
!entries.droppables[id] ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot update the scroll on Droppable " + id + " as it is not registered") : invariant(false) : void 0;
if (!collection) {
return;
}
callbacks.updateDroppableIsEnabled({
id: id,
isEnabled: isEnabled
});
};
var updateDroppableScroll = function updateDroppableScroll(id, newScroll) {
!entries.droppables[id] ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot update the scroll on Droppable " + id + " as it is not registered") : invariant(false) : void 0;
if (!collection) {
return;
}
callbacks.updateDroppableScroll({
id: id,
offset: newScroll
});
};
var scrollDroppable = function scrollDroppable(id, change) {
var entry = entries.droppables[id];
!entry ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot scroll Droppable " + id + " as it is not registered") : invariant(false) : void 0;
if (!collection) {
return;
}
entry.callbacks.scroll(change);
};
var getInitialPublish = function getInitialPublish(args) {
var critical = args.critical,
scrollOptions = args.scrollOptions,
windowScroll = args.initialWindowScroll;
var timingKey = 'Initial collection from DOM';
start(timingKey);
var home = critical.droppable;
var droppables = _Object$keys(entries.droppables).map(function (id) {
return entries.droppables[id];
}).filter(function (entry) {
return entry.descriptor.type === home.type;
}).map(function (entry) {
return entry.callbacks.getDimensionAndWatchScroll(windowScroll, scrollOptions);
}).reduce(function (previous, dimension) {
previous[dimension.descriptor.id] = dimension;
return previous;
}, {});
var draggables = _Object$keys(entries.draggables).map(function (id) {
return entries.draggables[id];
}).filter(function (entry) {
return entry.descriptor.type === critical.draggable.type;
}).map(function (entry) {
return entry.getDimension(windowScroll);
}).reduce(function (previous, dimension) {
previous[dimension.descriptor.id] = dimension;
return previous;
}, {});
finish(timingKey);
var dimensions = {
draggables: draggables,
droppables: droppables
};
var result = {
dimensions: dimensions,
critical: critical
};
return result;
};
var stopPublishing = function stopPublishing() {
if (!collection) {
return;
}
publisher.stop();
var home = collection.critical.droppable;
_Object$keys(entries.droppables).filter(function (id) {
return entries.droppables[id].descriptor.type === home.type;
}).forEach(function (id) {
return entries.droppables[id].callbacks.unwatchScroll();
});
collection = null;
};
var startPublishing = function startPublishing(request, windowScroll) {
!!collection ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot start capturing critical dimensions as there is already a collection') : invariant(false) : void 0;
var entry = entries.draggables[request.draggableId];
!entry ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot find critical draggable entry') : invariant(false) : void 0;
var home = entries.droppables[entry.descriptor.droppableId];
!home ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot find critical droppable entry') : invariant(false) : void 0;
var critical = {
draggable: entry.descriptor,
droppable: home.descriptor
};
collection = {
scrollOptions: request.scrollOptions,
critical: critical,
initialWindowScroll: windowScroll
};
return getInitialPublish(collection);
};
var marshal = {
registerDraggable: registerDraggable,
updateDraggable: updateDraggable,
unregisterDraggable: unregisterDraggable,
registerDroppable: registerDroppable,
updateDroppable: updateDroppable,
unregisterDroppable: unregisterDroppable,
updateDroppableIsEnabled: updateDroppableIsEnabled,
scrollDroppable: scrollDroppable,
updateDroppableScroll: updateDroppableScroll,
startPublishing: startPublishing,
stopPublishing: stopPublishing
};
return marshal;
});
var physics = function () {
var base = {
stiffness: 1000,
damping: 60,
precision: 0.99
};
var standard = _extends({}, base);
var fast = _extends({}, base, {
stiffness: base.stiffness * 2
});
return {
standard: standard,
fast: fast
};
}();
var css = {
outOfTheWay: 'transform 0.2s cubic-bezier(0.2, 0, 0, 1)'
};
var prefix = 'data-react-beautiful-dnd';
var dragHandle = prefix + "-drag-handle";
var draggable = prefix + "-draggable";
var droppable = prefix + "-droppable";
var getStyles = (function (styleContext) {
var dragHandleSelector = "[" + dragHandle + "=\"" + styleContext + "\"]";
var draggableSelector = "[" + draggable + "=\"" + styleContext + "\"]";
var droppableSelector = "[" + droppable + "=\"" + styleContext + "\"]";
var dragHandleStyles = {
base: "\n " + dragHandleSelector + " {\n -webkit-touch-callout: none;\n -webkit-tap-highlight-color: rgba(0,0,0,0);\n touch-action: manipulation;\n }\n ",
grabCursor: "\n " + dragHandleSelector + " {\n cursor: -webkit-grab;\n cursor: grab;\n }\n ",
blockPointerEvents: "\n " + dragHandleSelector + " {\n pointer-events: none;\n }\n "
};
var draggableStyles = {
animateMovement: "\n " + draggableSelector + " {\n transition: " + css.outOfTheWay + ";\n }\n "
};
var droppableStyles = {
base: "\n " + droppableSelector + " {\n overflow-anchor: none;\n }\n "
};
var bodyStyles = {
whileActiveDragging: "\n body {\n cursor: grabbing;\n cursor: -webkit-grabbing;\n user-select: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n }\n "
};
var base = [dragHandleStyles.base, droppableStyles.base];
var resting = base.concat([dragHandleStyles.grabCursor]);
var collecting = base.concat([dragHandleStyles.blockPointerEvents, bodyStyles.whileActiveDragging]);
var dragging = collecting.concat([draggableStyles.animateMovement]);
var dropAnimating = base.concat([dragHandleStyles.grabCursor, draggableStyles.animateMovement]);
var userCancel = base.concat([draggableStyles.animateMovement]);
return {
resting: resting.join(''),
dragging: dragging.join(''),
dropAnimating: dropAnimating.join(''),
collecting: collecting.join(''),
userCancel: userCancel.join('')
};
});
var count = 0;
var resetStyleContext = function resetStyleContext() {
count = 0;
};
var getHead = function getHead() {
var head = document.querySelector('head');
!head ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot find the head to append a style to') : invariant(false) : void 0;
return head;
};
var createStyleMarshal = (function () {
var context = "" + count++;
var styles = getStyles(context);
var el = null;
var setStyle = memoizeOne(function (proposed) {
!el ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot set style of style tag if not mounted') : invariant(false) : void 0;
el.innerHTML = proposed;
});
var mount = function mount() {
!!el ? process.env.NODE_ENV !== "production" ? invariant(false, 'Style marshal already mounted') : invariant(false) : void 0;
el = document.createElement('style');
el.type = 'text/css';
el.setAttribute(prefix, context);
getHead().appendChild(el);
setStyle(styles.resting);
};
var collecting = function collecting() {
return setStyle(styles.collecting);
};
var dragging = function dragging() {
return setStyle(styles.dragging);
};
var dropping = function dropping(reason) {
if (reason === 'DROP') {
setStyle(styles.dropAnimating);
return;
}
setStyle(styles.userCancel);
};
var resting = function resting() {
return setStyle(styles.resting);
};
var unmount = function unmount() {
!el ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot unmount style marshal as it is already unmounted') : invariant(false) : void 0;
getHead().removeChild(el);
el = null;
};
var marshal = {
collecting: collecting,
dragging: dragging,
dropping: dropping,
resting: resting,
styleContext: context,
mount: mount,
unmount: unmount
};
return marshal;
});
var canStartDrag = (function (state, id) {
if (state.phase === 'IDLE') {
return true;
}
if (state.phase !== 'DROP_ANIMATING') {
return false;
}
if (state.pending.result.draggableId === id) {
return false;
}
return state.pending.result.reason === 'DROP';
});
var scrollWindow = (function (change) {
window.scrollBy(change.x, change.y);
});
var count$1 = 0;
var visuallyHidden = {
position: 'absolute',
width: '1px',
height: '1px',
margin: '-1px',
border: '0',
padding: '0',
overflow: 'hidden',
clip: 'rect(0 0 0 0)',
'clip-path': 'inset(100%)'
};
var getBody = function getBody() {
!document.body ? process.env.NODE_ENV !== "production" ? invariant(false, 'Announcer cannot find document.body') : invariant(false) : void 0;
return document.body;
};
var createAnnouncer = (function () {
var id = "react-beautiful-dnd-announcement-" + count$1++;
var el = null;
var announce = function announce(message) {
!el ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot announce to unmounted node') : invariant(false) : void 0;
el.textContent = message;
};
var mount = function mount() {
!!el ? process.env.NODE_ENV !== "production" ? invariant(false, 'Announcer already mounted') : invariant(false) : void 0;
el = document.createElement('div');
el.id = id;
el.setAttribute('aria-live', 'assertive');
el.setAttribute('role', 'log');
el.setAttribute('aria-atomic', 'true');
_Object$assign(el.style, visuallyHidden);
getBody().appendChild(el);
};
var unmount = function unmount() {
!el ? process.env.NODE_ENV !== "production" ? invariant(false, 'Will not unmount annoucer as it is already unmounted') : invariant(false) : void 0;
getBody().removeChild(el);
el = null;
};
var announcer = {
announce: announce,
id: id,
mount: mount,
unmount: unmount
};
return announcer;
});
var getScrollableDroppables = memoizeOne(function (droppables) {
return toDroppableList(droppables).filter(function (droppable) {
if (!droppable.isEnabled) {
return false;
}
if (!droppable.viewport.closestScrollable) {
return false;
}
return true;
});
});
var getScrollableDroppableOver = function getScrollableDroppableOver(target, droppables) {
var maybe = getScrollableDroppables(droppables).find(function (droppable) {
!droppable.viewport.closestScrollable ? process.env.NODE_ENV !== "production" ? invariant(false, 'Invalid result') : invariant(false) : void 0;
return isPositionInFrame(droppable.viewport.closestScrollable.framePageMarginBox)(target);
});
return maybe;
};
var getBestScrollableDroppable = (function (_ref) {
var center = _ref.center,
destination = _ref.destination,
droppables = _ref.droppables;
if (destination) {
var _dimension = droppables[destination.droppableId];
if (!_dimension.viewport.closestScrollable) {
return null;
}
return _dimension;
}
var dimension = getScrollableDroppableOver(center, droppables);
return dimension;
});
var smallestSigned = apply(function (value) {
if (value === 0) {
return 0;
}
return value > 0 ? 1 : -1;
});
var getOverlap = function () {
var getRemainder = function getRemainder(target, max) {
if (target < 0) {
return target;
}
if (target > max) {
return target - max;
}
return 0;
};
return function (_ref) {
var current = _ref.current,
max = _ref.max,
change = _ref.change;
var targetScroll = add(current, change);
var overlap = {
x: getRemainder(targetScroll.x, max.x),
y: getRemainder(targetScroll.y, max.y)
};
if (isEqual(overlap, origin)) {
return null;
}
return overlap;
};
}();
var canPartiallyScroll = function canPartiallyScroll(_ref2) {
var rawMax = _ref2.max,
current = _ref2.current,
change = _ref2.change;
var max = {
x: Math.max(current.x, rawMax.x),
y: Math.max(current.y, rawMax.y)
};
var smallestChange = smallestSigned(change);
var overlap = getOverlap({
max: max,
current: current,
change: smallestChange
});
if (!overlap) {
return true;
}
if (smallestChange.x !== 0 && overlap.x === 0) {
return true;
}
if (smallestChange.y !== 0 && overlap.y === 0) {
return true;
}
return false;
};
var canScrollWindow = function canScrollWindow(viewport, change) {
return canPartiallyScroll({
current: viewport.scroll.current,
max: viewport.scroll.max,
change: change
});
};
var getWindowOverlap = function getWindowOverlap(viewport, change) {
if (!canScrollWindow(viewport, change)) {
return null;
}
var max = viewport.scroll.max;
var current = viewport.scroll.current;
return getOverlap({
current: current,
max: max,
change: change
});
};
var canScrollDroppable = function canScrollDroppable(droppable, change) {
var closest$$1 = droppable.viewport.closestScrollable;
if (!closest$$1) {
return false;
}
return canPartiallyScroll({
current: closest$$1.scroll.current,
max: closest$$1.scroll.max,
change: change
});
};
var getDroppableOverlap = function getDroppableOverlap(droppable, change) {
var closest$$1 = droppable.viewport.closestScrollable;
if (!closest$$1) {
return null;
}
if (!canScrollDroppable(droppable, change)) {
return null;
}
return getOverlap({
current: closest$$1.scroll.current,
max: closest$$1.scroll.max,
change: change
});
};
var config = {
startFrom: 0.25,
maxSpeedAt: 0.05,
maxScrollSpeed: 28,
ease: function ease(percentage) {
return Math.pow(percentage, 2);
}
};
var clean$1 = apply(function (value) {
return value === 0 ? 0 : value;
});
var getPixelThresholds = function getPixelThresholds(container, axis) {
var startFrom = container[axis.size] * config.startFrom;
var maxSpeedAt = container[axis.size] * config.maxSpeedAt;
var accelerationPlane = startFrom - maxSpeedAt;
var thresholds = {
startFrom: startFrom,
maxSpeedAt: maxSpeedAt,
accelerationPlane: accelerationPlane
};
return thresholds;
};
var getSpeed = function getSpeed(distance$$1, thresholds) {
if (distance$$1 >= thresholds.startFrom) {
return 0;
}
if (distance$$1 <= thresholds.maxSpeedAt) {
return config.maxScrollSpeed;
}
var distancePastStart = thresholds.startFrom - distance$$1;
var percentage = distancePastStart / thresholds.accelerationPlane;
var transformed = config.ease(percentage);
var speed = config.maxScrollSpeed * transformed;
return speed;
};
var adjustForSizeLimits = function adjustForSizeLimits(_ref) {
var container = _ref.container,
subject = _ref.subject,
proposedScroll = _ref.proposedScroll;
var isTooBigVertically = subject.height > container.height;
var isTooBigHorizontally = subject.width > container.width;
if (!isTooBigHorizontally && !isTooBigVertically) {
return proposedScroll;
}
if (isTooBigHorizontally && isTooBigVertically) {
return null;
}
return {
x: isTooBigHorizontally ? 0 : proposedScroll.x,
y: isTooBigVertically ? 0 : proposedScroll.y
};
};
var getRequiredScroll = function getRequiredScroll(_ref2) {
var container = _ref2.container,
subject = _ref2.subject,
center = _ref2.center;
var distance$$1 = {
top: center.y - container.top,
right: container.right - center.x,
bottom: container.bottom - center.y,
left: center.x - container.left
};
var y = function () {
var thresholds = getPixelThresholds(container, vertical);
var isCloserToBottom = distance$$1.bottom < distance$$1.top;
if (isCloserToBottom) {
return getSpeed(distance$$1.bottom, thresholds);
}
return -1 * getSpeed(distance$$1.top, thresholds);
}();
var x = function () {
var thresholds = getPixelThresholds(container, horizontal);
var isCloserToRight = distance$$1.right < distance$$1.left;
if (isCloserToRight) {
return getSpeed(distance$$1.right, thresholds);
}
return -1 * getSpeed(distance$$1.left, thresholds);
}();
var required = clean$1({
x: x,
y: y
});
if (isEqual(required, origin)) {
return null;
}
var limited = adjustForSizeLimits({
container: container,
subject: subject,
proposedScroll: required
});
if (!limited) {
return null;
}
return isEqual(limited, origin) ? null : limited;
};
var withPlaceholder = function withPlaceholder(droppable, draggable) {
var closest$$1 = droppable.viewport.closestScrollable;
if (!closest$$1) {
return null;
}
var isOverHome = droppable.descriptor.id === draggable.descriptor.droppableId;
var max = closest$$1.scroll.max;
var current = closest$$1.scroll.current;
if (isOverHome) {
return {
max: max,
current: current
};
}
var spaceForPlaceholder = patch(droppable.axis.line, draggable.placeholder.client.borderBox[droppable.axis.size]);
var newMax = add(max, spaceForPlaceholder);
var newCurrent = {
x: Math.min(current.x, newMax.x),
y: Math.min(current.y, newMax.y)
};
return {
max: newMax,
current: newCurrent
};
};
var createFluidScroller = (function (_ref3) {
var scrollWindow = _ref3.scrollWindow,
scrollDroppable = _ref3.scrollDroppable;
var scheduleWindowScroll = rafSchd(scrollWindow);
var scheduleDroppableScroll = rafSchd(scrollDroppable);
var scroller = function scroller(state) {
var center = state.current.page.borderBoxCenter;
var draggable = state.dimensions.draggables[state.critical.draggable.id];
var subject = draggable.page.marginBox;
var viewport = state.viewport;
var requiredWindowScroll = getRequiredScroll({
container: viewport.frame,
subject: subject,
center: center
});
if (requiredWindowScroll && canScrollWindow(viewport, requiredWindowScroll)) {
scheduleWindowScroll(requiredWindowScroll);
return;
}
var droppable = getBestScrollableDroppable({
center: center,
destination: state.impact.destination,
droppables: state.dimensions.droppables
});
if (!droppable) {
return;
}
var closestScrollable = droppable.viewport.closestScrollable;
if (!closestScrollable) {
return;
}
var requiredFrameScroll = getRequiredScroll({
container: closestScrollable.framePageMarginBox,
subject: subject,
center: center
});
if (!requiredFrameScroll) {
return;
}
var result = withPlaceholder(droppable, draggable);
if (!result) {
return;
}
var closest$$1 = droppable.viewport.closestScrollable;
if (!closest$$1) {
return;
}
var canScrollDroppable$$1 = canPartiallyScroll({
current: result.current,
max: result.max,
change: requiredFrameScroll
});
if (canScrollDroppable$$1) {
scheduleDroppableScroll(droppable.descriptor.id, requiredFrameScroll);
}
};
scroller.cancel = function () {
scheduleWindowScroll.cancel();
scheduleDroppableScroll.cancel();
};
return scroller;
});
var createJumpScroller = (function (_ref) {
var move = _ref.move,
scrollDroppable = _ref.scrollDroppable,
scrollWindow = _ref.scrollWindow;
var moveByOffset = function moveByOffset(state, offset) {
var client = add(state.current.client.selection, offset);
move({
client: client,
shouldAnimate: true
});
};
var scrollDroppableAsMuchAsItCan = function scrollDroppableAsMuchAsItCan(droppable, change) {
if (!canScrollDroppable(droppable, change)) {
return change;
}
var overlap = getDroppableOverlap(droppable, change);
if (!overlap) {
scrollDroppable(droppable.descriptor.id, change);
return null;
}
var whatTheDroppableCanScroll = subtract(change, overlap);
scrollDroppable(droppable.descriptor.id, whatTheDroppableCanScroll);
var remainder = subtract(change, whatTheDroppableCanScroll);
return remainder;
};
var scrollWindowAsMuchAsItCan = function scrollWindowAsMuchAsItCan(viewport, change) {
if (!canScrollWindow(viewport, change)) {
return change;
}
var overlap = getWindowOverlap(viewport, change);
if (!overlap) {
scrollWindow(change);
return null;
}
var whatTheWindowCanScroll = subtract(change, overlap);
scrollWindow(whatTheWindowCanScroll);
var remainder = subtract(change, whatTheWindowCanScroll);
return remainder;
};
var jumpScroller = function jumpScroller(state) {
var request = state.scrollJumpRequest;
if (!request) {
return;
}
var destination = state.impact.destination;
!destination ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot perform a jump scroll when there is no destination') : invariant(false) : void 0;
var droppableRemainder = scrollDroppableAsMuchAsItCan(state.dimensions.droppables[destination.droppableId], request);
if (!droppableRemainder) {
return;
}
var viewport = state.viewport;
var windowRemainder = scrollWindowAsMuchAsItCan(viewport, droppableRemainder);
if (!windowRemainder) {
return;
}
moveByOffset(state, windowRemainder);
};
return jumpScroller;
});
var createAutoScroller = (function (_ref) {
var scrollDroppable = _ref.scrollDroppable,
scrollWindow = _ref.scrollWindow,
move = _ref.move;
var fluidScroll = createFluidScroller({
scrollWindow: scrollWindow,
scrollDroppable: scrollDroppable
});
var jumpScroll = createJumpScroller({
move: move,
scrollWindow: scrollWindow,
scrollDroppable: scrollDroppable
});
var marshal = {
cancel: fluidScroll.cancel,
fluidScroll: fluidScroll,
jumpScroll: jumpScroll
};
return marshal;
});
var prefix$1 = function prefix(key) {
return "private-react-beautiful-dnd-key-do-not-use-" + key;
};
var storeKey = prefix$1('store');
var droppableIdKey = prefix$1('droppable-id');
var droppableTypeKey = prefix$1('droppable-type');
var dimensionMarshalKey = prefix$1('dimension-marshal');
var styleContextKey = prefix$1('style-context');
var canLiftContextKey = prefix$1('can-lift');
var _DragDropContext$chil;
var resetServerContext = function resetServerContext() {
resetStyleContext();
};
var printFatalDevError = function printFatalDevError(error) {
if (process.env.NODE_ENV === 'production') {
return;
}
console.warn("\n An error has occurred while a drag is occurring.\n Any existing drag will be cancelled.\n\n Raw error:\n ");
console.error(error);
};
var DragDropContext = function (_React$Component) {
_inheritsLoose(DragDropContext, _React$Component);
function DragDropContext(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
_this.store = void 0;
_this.dimensionMarshal = void 0;
_this.styleMarshal = void 0;
_this.autoScroller = void 0;
_this.announcer = void 0;
_this.unsubscribe = void 0;
_this.canLift = function (id) {
return canStartDrag(_this.store.getState(), id);
};
_this.onFatalError = function (error) {
printFatalDevError(error);
var state = _this.store.getState();
if (state.phase !== 'IDLE') {
_this.store.dispatch(clean());
}
};
_this.onWindowError = function (error) {
return _this.onFatalError(error);
};
_this.announcer = createAnnouncer();
_this.styleMarshal = createStyleMarshal();
_this.store = createStore({
getDimensionMarshal: function getDimensionMarshal() {
return _this.dimensionMarshal;
},
styleMarshal: _this.styleMarshal,
getHooks: function getHooks() {
return {
onBeforeDragStart: _this.props.onBeforeDragStart,
onDragStart: _this.props.onDragStart,
onDragEnd: _this.props.onDragEnd,
onDragUpdate: _this.props.onDragUpdate
};
},
announce: _this.announcer.announce,
getScroller: function getScroller() {
return _this.autoScroller;
}
});
var callbacks = redux.bindActionCreators({
collectionStarting: collectionStarting,
publish: publish,
updateDroppableScroll: updateDroppableScroll,
updateDroppableIsEnabled: updateDroppableIsEnabled
}, _this.store.dispatch);
_this.dimensionMarshal = createDimensionMarshal(callbacks);
_this.autoScroller = createAutoScroller(_extends({
scrollWindow: scrollWindow,
scrollDroppable: _this.dimensionMarshal.scrollDroppable
}, redux.bindActionCreators({
move: move
}, _this.store.dispatch)));
return _this;
}
var _proto = DragDropContext.prototype;
_proto.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[storeKey] = this.store, _ref[dimensionMarshalKey] = this.dimensionMarshal, _ref[styleContextKey] = this.styleMarshal.styleContext, _ref[canLiftContextKey] = this.canLift, _ref;
};
_proto.componentDidMount = function componentDidMount() {
window.addEventListener('error', this.onWindowError);
this.styleMarshal.mount();
this.announcer.mount();
};
_proto.componentDidCatch = function componentDidCatch(error) {
this.onFatalError(error);
if (error.message.indexOf('Invariant failed') !== -1) {
this.setState({});
return;
}
throw error;
};
_proto.componentWillUnmount = function componentWillUnmount() {
window.removeEventListener('error', this.onWindowError);
var state = this.store.getState();
if (state.phase !== 'IDLE') {
this.store.dispatch(clean());
}
this.styleMarshal.unmount();
this.announcer.unmount();
};
_proto.render = function render() {
return this.props.children;
};
return DragDropContext;
}(React__default.Component);
DragDropContext.childContextTypes = (_DragDropContext$chil = {}, _DragDropContext$chil[storeKey] = PropTypes.shape({
dispatch: PropTypes.func.isRequired,
subscribe: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired
}).isRequired, _DragDropContext$chil[dimensionMarshalKey] = PropTypes.object.isRequired, _DragDropContext$chil[styleContextKey] = PropTypes.string.isRequired, _DragDropContext$chil[canLiftContextKey] = PropTypes.func.isRequired, _DragDropContext$chil);
var isScrollable = function isScrollable() {
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
values[_key] = arguments[_key];
}
return values.some(function (value) {
return value === 'auto' || value === 'scroll';
});
};
var isElementScrollable = function isElementScrollable(el) {
var style = window.getComputedStyle(el);
return isScrollable(style.overflow, style.overflowY, style.overflowX);
};
var getClosestScrollable = function getClosestScrollable(el) {
if (el == null) {
return null;
}
if (!isElementScrollable(el)) {
return getClosestScrollable(el.parentElement);
}
return el;
};
var _DroppableDimensionPu;
var getScroll = function getScroll(el) {
return {
x: el.scrollLeft,
y: el.scrollTop
};
};
var checkForNestedScrollContainers = function checkForNestedScrollContainers(scrollable) {
if (process.env.NODE_ENV === 'production') {
return;
}
if (!scrollable) {
return;
}
var anotherScrollParent = getClosestScrollable(scrollable.parentElement);
if (!anotherScrollParent) {
return;
}
console.warn("\n Droppable: unsupported nested scroll container detected.\n A Droppable can only have one scroll parent (which can be itself)\n Nested scroll containers are currently not supported.\n\n We hope to support nested scroll containers soon: https://github.com/atlassian/react-beautiful-dnd/issues/131\n ");
};
var listenerOptions = {
passive: true
};
var DroppableDimensionPublisher = function (_React$Component) {
_inheritsLoose(DroppableDimensionPublisher, _React$Component);
function DroppableDimensionPublisher(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
_this.watchingScroll = null;
_this.callbacks = void 0;
_this.publishedDescriptor = null;
_this.getClosestScroll = function () {
if (!_this.watchingScroll) {
return origin;
}
return getScroll(_this.watchingScroll.closestScrollable);
};
_this.memoizedUpdateScroll = memoizeOne(function (x, y) {
!_this.publishedDescriptor ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot update scroll on unpublished droppable') : invariant(false) : void 0;
var newScroll = {
x: x,
y: y
};
var marshal = _this.context[dimensionMarshalKey];
marshal.updateDroppableScroll(_this.publishedDescriptor.id, newScroll);
});
_this.updateScroll = function () {
var offset = _this.getClosestScroll();
_this.memoizedUpdateScroll(offset.x, offset.y);
};
_this.scheduleScrollUpdate = rafSchd(_this.updateScroll);
_this.onClosestScroll = function () {
!_this.watchingScroll ? process.env.NODE_ENV !== "production" ? invariant(false, 'Could not find scroll options while scrolling') : invariant(false) : void 0;
var options = _this.watchingScroll.options;
if (options.shouldPublishImmediately) {
_this.updateScroll();
return;
}
_this.scheduleScrollUpdate();
};
_this.scroll = function (change) {
!_this.watchingScroll ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot scroll a droppable with no closest scrollable') : invariant(false) : void 0;
var closestScrollable = _this.watchingScroll.closestScrollable;
closestScrollable.scrollTop += change.y;
closestScrollable.scrollLeft += change.x;
};
_this.watchScroll = function (closestScrollable, options) {
!!_this.watchingScroll ? process.env.NODE_ENV !== "production" ? invariant(false, 'Droppable cannot watch scroll as it is already watching scroll') : invariant(false) : void 0;
if (!closestScrollable) {
return;
}
_this.watchingScroll = {
options: options,
closestScrollable: closestScrollable
};
closestScrollable.addEventListener('scroll', _this.onClosestScroll, listenerOptions);
};
_this.unwatchScroll = function () {
var watching = _this.watchingScroll;
if (!watching) {
return;
}
_this.scheduleScrollUpdate.cancel();
watching.closestScrollable.removeEventListener('scroll', _this.onClosestScroll, listenerOptions);
_this.watchingScroll = null;
};
_this.getMemoizedDescriptor = memoizeOne(function (id, type) {
return {
id: id,
type: type
};
});
_this.publish = function () {
var marshal = _this.context[dimensionMarshalKey];
var descriptor = _this.getMemoizedDescriptor(_this.props.droppableId, _this.props.type);
if (!_this.publishedDescriptor) {
marshal.registerDroppable(descriptor, _this.callbacks);
_this.publishedDescriptor = descriptor;
return;
}
if (_this.publishedDescriptor === descriptor) {
return;
}
marshal.updateDroppable(_this.publishedDescriptor, descriptor, _this.callbacks);
_this.publishedDescriptor = descriptor;
};
_this.unpublish = function () {
!_this.publishedDescriptor ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot unpublish descriptor when none is published') : invariant(false) : void 0;
var marshal = _this.context[dimensionMarshalKey];
marshal.unregisterDroppable(_this.publishedDescriptor);
_this.publishedDescriptor = null;
};
_this.getDimensionAndWatchScroll = function (windowScroll, options) {
var _this$props = _this.props,
direction = _this$props.direction,
ignoreContainerClipping = _this$props.ignoreContainerClipping,
isDropDisabled = _this$props.isDropDisabled,
getDroppableRef = _this$props.getDroppableRef;
var targetRef = getDroppableRef();
var descriptor = _this.publishedDescriptor;
!targetRef ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot calculate a dimension when not attached to the DOM') : invariant(false) : void 0;
!descriptor ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot get dimension for unpublished droppable') : invariant(false) : void 0;
var scrollableRef = getClosestScrollable(targetRef);
checkForNestedScrollContainers(scrollableRef);
_this.watchScroll(scrollableRef, options);
var client = function () {
var base = cssBoxModel.getBox(targetRef);
if (!scrollableRef) {
return base;
}
if (targetRef !== scrollableRef) {
return base;
}
var top = base.paddingBox.top - scrollableRef.scrollTop;
var left = base.paddingBox.left - scrollableRef.scrollLeft;
var bottom = top + scrollableRef.scrollHeight;
var right = left + scrollableRef.scrollWidth;
var paddingBox = {
top: top,
right: right,
bottom: bottom,
left: left
};
var borderBox = {
top: paddingBox.top - base.border.top,
right: paddingBox.right + base.border.right,
bottom: paddingBox.bottom + base.border.bottom,
left: paddingBox.left - base.border.left
};
return cssBoxModel.createBox({
borderBox: borderBox,
margin: base.margin,
border: base.border,
padding: base.padding
});
}();
var page = cssBoxModel.withScroll(client, windowScroll);
var closest$$1 = function () {
if (!scrollableRef) {
return null;
}
var frameClient = cssBoxModel.getBox(scrollableRef);
return {
client: frameClient,
page: cssBoxModel.withScroll(frameClient),
scrollHeight: scrollableRef.scrollHeight,
scrollWidth: scrollableRef.scrollWidth,
scroll: getScroll(scrollableRef),
shouldClipSubject: !ignoreContainerClipping
};
}();
return getDroppableDimension({
descriptor: descriptor,
isEnabled: !isDropDisabled,
direction: direction,
client: client,
page: page,
closest: closest$$1
});
};
var callbacks = {
getDimensionAndWatchScroll: _this.getDimensionAndWatchScroll,
unwatchScroll: _this.unwatchScroll,
scroll: _this.scroll
};
_this.callbacks = callbacks;
return _this;
}
var _proto = DroppableDimensionPublisher.prototype;
_proto.componentDidMount = function componentDidMount() {
this.publish();
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
this.publish();
if (this.props.isDropDisabled === prevProps.isDropDisabled) {
return;
}
var marshal = this.context[dimensionMarshalKey];
marshal.updateDroppableIsEnabled(this.props.droppableId, !this.props.isDropDisabled);
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.watchingScroll) {
if (process.env.NODE_ENV !== 'production') {
console.warn('Unmounting droppable while it was watching scroll');
}
this.unwatchScroll();
}
this.unpublish();
};
_proto.render = function render() {
return this.props.children;
};
return DroppableDimensionPublisher;
}(React__default.Component);
DroppableDimensionPublisher.contextTypes = (_DroppableDimensionPu = {}, _DroppableDimensionPu[dimensionMarshalKey] = PropTypes.object.isRequired, _DroppableDimensionPu);
var Placeholder = function (_PureComponent) {
_inheritsLoose(Placeholder, _PureComponent);
function Placeholder() {
return _PureComponent.apply(this, arguments) || this;
}
var _proto = Placeholder.prototype;
_proto.componentDidMount = function componentDidMount() {
if (this.props.onMount) {
this.props.onMount();
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.props.onUnmount) {
this.props.onUnmount();
}
};
_proto.render = function render() {
var placeholder = this.props.placeholder;
var client = placeholder.client,
display = placeholder.display,
tagName = placeholder.tagName;
var style = {
display: display,
boxSizing: 'border-box',
width: client.borderBox.width,
height: client.borderBox.height,
marginTop: client.margin.top,
marginRight: client.margin.right,
marginBottom: client.margin.bottom,
marginLeft: client.margin.left,
flexShrink: '0',
flexGrow: '0',
pointerEvents: 'none'
};
return React__default.createElement(tagName, {
style: style
});
};
return Placeholder;
}(React.PureComponent);
var throwIfRefIsInvalid = (function (ref) {
!(ref && ref instanceof HTMLElement) ? process.env.NODE_ENV !== "production" ? invariant(false, "\n provided.innerRef has not been provided with a HTMLElement.\n\n You can find a guide on using the innerRef callback functions at:\n https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/using-inner-ref.md\n ") : invariant(false) : void 0;
});
var _Droppable$contextTyp, _Droppable$childConte;
var Droppable = function (_Component) {
_inheritsLoose(Droppable, _Component);
function Droppable(props, context) {
var _this;
_this = _Component.call(this, props, context) || this;
_this.styleContext = void 0;
_this.ref = null;
_this.isPlaceholderMounted = false;
_this.onPlaceholderMount = function () {
_this.isPlaceholderMounted = true;
};
_this.onPlaceholderUnmount = function () {
_this.isPlaceholderMounted = false;
};
_this.setRef = function (ref) {
if (ref === null) {
return;
}
if (ref === _this.ref) {
return;
}
_this.ref = ref;
throwIfRefIsInvalid(ref);
};
_this.getDroppableRef = function () {
return _this.ref;
};
_this.styleContext = context[styleContextKey];
return _this;
}
var _proto = Droppable.prototype;
_proto.getChildContext = function getChildContext() {
var _value;
var value = (_value = {}, _value[droppableIdKey] = this.props.droppableId, _value[droppableTypeKey] = this.props.type, _value);
return value;
};
_proto.componentDidMount = function componentDidMount() {
throwIfRefIsInvalid(this.ref);
this.warnIfPlaceholderNotMounted();
};
_proto.componentDidUpdate = function componentDidUpdate() {
this.warnIfPlaceholderNotMounted();
};
_proto.warnIfPlaceholderNotMounted = function warnIfPlaceholderNotMounted() {
if (process.env.NODE_ENV === 'production') {
return;
}
if (!this.props.placeholder) {
return;
}
if (this.isPlaceholderMounted) {
return;
}
console.warn("\n Droppable setup issue: DroppableProvided > placeholder could not be found.\n Please be sure to add the {provided.placeholder} Node as a child of your Droppable\n\n More information: https://github.com/atlassian/react-beautiful-dnd#1-provided-droppableprovided\n ");
};
_proto.getPlaceholder = function getPlaceholder() {
if (!this.props.placeholder) {
return null;
}
return React__default.createElement(Placeholder, {
placeholder: this.props.placeholder,
onMount: this.onPlaceholderMount,
onUnmount: this.onPlaceholderUnmount
});
};
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
direction = _this$props.direction,
droppableId = _this$props.droppableId,
ignoreContainerClipping = _this$props.ignoreContainerClipping,
isDraggingOver = _this$props.isDraggingOver,
isDropDisabled = _this$props.isDropDisabled,
draggingOverWith = _this$props.draggingOverWith,
type = _this$props.type;
var provided = {
innerRef: this.setRef,
placeholder: this.getPlaceholder(),
droppableProps: {
'data-react-beautiful-dnd-droppable': this.styleContext
}
};
var snapshot = {
isDraggingOver: isDraggingOver,
draggingOverWith: draggingOverWith
};
return React__default.createElement(DroppableDimensionPublisher, {
droppableId: droppableId,
type: type,
direction: direction,
ignoreContainerClipping: ignoreContainerClipping,
isDropDisabled: isDropDisabled,
getDroppableRef: this.getDroppableRef
}, children(provided, snapshot));
};
return Droppable;
}(React.Component);
Droppable.contextTypes = (_Droppable$contextTyp = {}, _Droppable$contextTyp[styleContextKey] = PropTypes.string.isRequired, _Droppable$contextTyp);
Droppable.childContextTypes = (_Droppable$childConte = {}, _Droppable$childConte[droppableIdKey] = PropTypes.string.isRequired, _Droppable$childConte[droppableTypeKey] = PropTypes.string.isRequired, _Droppable$childConte);
var isStrictEqual = (function (a, b) {
return a === b;
});
var makeMapStateToProps = function makeMapStateToProps() {
var getIsDraggingOver = function getIsDraggingOver(id, destination) {
if (!destination) {
return false;
}
return destination.droppableId === id;
};
var shouldUsePlaceholder = function shouldUsePlaceholder(id, descriptor, destination) {
if (!destination) {
return false;
}
if (id === descriptor.droppableId) {
return false;
}
return id === destination.droppableId;
};
var getMapProps = memoizeOne(function (isDraggingOver, draggingOverWith, placeholder) {
return {
isDraggingOver: isDraggingOver,
draggingOverWith: draggingOverWith,
placeholder: placeholder
};
});
var getDefault = function getDefault() {
return getMapProps(false, null, null);
};
var selector = function selector(state, ownProps) {
if (ownProps.isDropDisabled) {
return getDefault();
}
var id = ownProps.droppableId;
if (state.isDragging) {
var destination = state.impact.destination;
var isDraggingOver = getIsDraggingOver(id, destination);
var draggableId = state.critical.draggable.id;
var draggingOverWith = isDraggingOver ? draggableId : null;
var draggable = state.dimensions.draggables[draggableId];
var placeholder = shouldUsePlaceholder(id, draggable.descriptor, destination) ? draggable.placeholder : null;
return getMapProps(isDraggingOver, draggingOverWith, placeholder);
}
if (state.phase === 'DROP_ANIMATING') {
var _destination = state.pending.impact.destination;
var _isDraggingOver = getIsDraggingOver(id, _destination);
var _draggableId = state.pending.result.draggableId;
var _draggingOverWith = _isDraggingOver ? _draggableId : null;
var _draggable = state.dimensions.draggables[_draggableId];
var _placeholder = shouldUsePlaceholder(id, _draggable.descriptor, _destination) ? _draggable.placeholder : null;
return getMapProps(_isDraggingOver, _draggingOverWith, _placeholder);
}
return getDefault();
};
return selector;
};
var connectedDroppable = reactRedux.connect(makeMapStateToProps, null, null, {
storeKey: storeKey,
pure: true,
areStatePropsEqual: isStrictEqual
})(Droppable);
connectedDroppable.defaultProps = {
type: 'DEFAULT',
isDropDisabled: false,
direction: 'vertical',
ignoreContainerClipping: false
};
var _DraggableDimensionPu;
var DraggableDimensionPublisher = function (_Component) {
_inheritsLoose(DraggableDimensionPublisher, _Component);
function DraggableDimensionPublisher() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _Component.call.apply(_Component, [this].concat(args)) || this;
_this.publishedDescriptor = null;
_this.getMemoizedDescriptor = memoizeOne(function (id, index, droppableId, type) {
return {
id: id,
index: index,
droppableId: droppableId,
type: type
};
});
_this.publish = function () {
var marshal = _this.context[dimensionMarshalKey];
var descriptor = _this.getMemoizedDescriptor(_this.props.draggableId, _this.props.index, _this.props.droppableId, _this.props.type);
if (!_this.publishedDescriptor) {
marshal.registerDraggable(descriptor, _this.getDimension);
_this.publishedDescriptor = descriptor;
return;
}
if (descriptor === _this.publishedDescriptor) {
return;
}
marshal.updateDraggable(_this.publishedDescriptor, descriptor, _this.getDimension);
_this.publishedDescriptor = descriptor;
};
_this.unpublish = function () {
!_this.publishedDescriptor ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot unpublish descriptor when none is published') : invariant(false) : void 0;
var marshal = _this.context[dimensionMarshalKey];
marshal.unregisterDraggable(_this.publishedDescriptor);
_this.publishedDescriptor = null;
};
_this.getDimension = function (windowScroll) {
var targetRef = _this.props.getDraggableRef();
var descriptor = _this.publishedDescriptor;
!targetRef ? process.env.NODE_ENV !== "production" ? invariant(false, 'DraggableDimensionPublisher cannot calculate a dimension when not attached to the DOM') : invariant(false) : void 0;
!descriptor ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot get dimension for unpublished draggable') : invariant(false) : void 0;
var computedStyles = window.getComputedStyle(targetRef);
var borderBox = targetRef.getBoundingClientRect();
var client = cssBoxModel.calculateBox(borderBox, computedStyles);
var page = cssBoxModel.withScroll(client, windowScroll);
var placeholder = {
client: client,
tagName: targetRef.tagName.toLowerCase(),
display: computedStyles.display
};
var dimension = {
descriptor: descriptor,
placeholder: placeholder,
client: client,
page: page
};
return dimension;
};
return _this;
}
var _proto = DraggableDimensionPublisher.prototype;
_proto.componentDidMount = function componentDidMount() {
this.publish();
};
_proto.componentDidUpdate = function componentDidUpdate() {
this.publish();
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.unpublish();
};
_proto.render = function render() {
return this.props.children;
};
return DraggableDimensionPublisher;
}(React.Component);
DraggableDimensionPublisher.contextTypes = (_DraggableDimensionPu = {}, _DraggableDimensionPu[dimensionMarshalKey] = PropTypes.object.isRequired, _DraggableDimensionPu);
var DoubleRenderBlocker = function (_React$Component) {
_inheritsLoose(DoubleRenderBlocker, _React$Component);
function DoubleRenderBlocker() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = DoubleRenderBlocker.prototype;
_proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
if (isEqual(origin, nextProps.change)) {
return true;
}
if (isEqual(this.props.change, nextProps.change)) {
return false;
}
return true;
};
_proto.render = function render() {
return this.props.children(this.props.change);
};
return DoubleRenderBlocker;
}(React__default.Component);
var Moveable = function (_Component) {
_inheritsLoose(Moveable, _Component);
function Moveable() {
return _Component.apply(this, arguments) || this;
}
var _proto2 = Moveable.prototype;
_proto2.getFinal = function getFinal() {
var destination = this.props.destination;
var speed = this.props.speed;
if (speed === 'INSTANT') {
return destination;
}
var config = speed === 'FAST' ? physics.fast : physics.standard;
return {
x: reactMotion.spring(destination.x, config),
y: reactMotion.spring(destination.y, config)
};
};
_proto2.render = function render() {
var _this = this;
var final = this.getFinal();
return React__default.createElement(reactMotion.Motion, {
defaultStyle: origin,
style: final,
onRest: this.props.onMoveEnd
}, function (current) {
var _this$props = _this.props,
speed = _this$props.speed,
destination = _this$props.destination,
children = _this$props.children;
var target = speed === 'INSTANT' ? destination : current;
return React__default.createElement(DoubleRenderBlocker, {
change: target
}, children);
});
};
return Moveable;
}(React.Component);
Moveable.defaultProps = {
destination: origin
};
var getWindowFromRef = (function (ref) {
return ref ? ref.ownerDocument.defaultView : window;
});
var selector = "[" + dragHandle + "]";
var isSVG = function isSVG(el) {
if (typeof SVGElement === 'undefined') {
return false;
}
return el instanceof SVGElement;
};
var throwIfSVG = function throwIfSVG(el) {
!!isSVG(el) ? process.env.NODE_ENV !== "production" ? invariant(false, "A drag handle cannot be an SVGElement: it has inconsistent focus support.\n\n More information: https://github.com/atlassian/react-beautiful-dnd/tree/master/docs/guides/dragging-svgs.md") : invariant(false) : void 0;
};
var getDragHandleRef = function getDragHandleRef(draggableRef) {
if (draggableRef.hasAttribute(dragHandle)) {
throwIfSVG(draggableRef);
return draggableRef;
}
var el = draggableRef.querySelector(selector);
throwIfSVG(draggableRef);
!el ? process.env.NODE_ENV !== "production" ? invariant(false, "\n Cannot find drag handle element inside of Draggable.\n Please be sure to apply the {...provided.dragHandleProps} to your Draggable\n\n More information: https://github.com/atlassian/react-beautiful-dnd#draggable\n ") : invariant(false) : void 0;
!(el instanceof HTMLElement) ? process.env.NODE_ENV !== "production" ? invariant(false, 'A drag handle must be a HTMLElement') : invariant(false) : void 0;
return el;
};
var retainingFocusFor = null;
var listenerOptions$1 = {
capture: true
};
var clearRetentionOnFocusChange = function () {
var isBound = false;
var bind = function bind() {
if (isBound) {
return;
}
isBound = true;
window.addEventListener('focus', onWindowFocusChange, listenerOptions$1);
};
var unbind = function unbind() {
if (!isBound) {
return;
}
isBound = false;
window.removeEventListener('focus', onWindowFocusChange, listenerOptions$1);
};
var onWindowFocusChange = function onWindowFocusChange() {
unbind();
retainingFocusFor = null;
};
var result = function result() {
return bind();
};
result.cancel = function () {
return unbind();
};
return result;
}();
var retain = function retain(id) {
retainingFocusFor = id;
clearRetentionOnFocusChange();
};
var tryRestoreFocus = function tryRestoreFocus(id, draggableRef) {
if (!retainingFocusFor) {
return;
}
if (id !== retainingFocusFor) {
return;
}
retainingFocusFor = null;
clearRetentionOnFocusChange.cancel();
var dragHandleRef = getDragHandleRef(draggableRef);
if (!dragHandleRef) {
console.warn('Could not find drag handle in the DOM to focus on it');
return;
}
dragHandleRef.focus();
};
var retainer = {
retain: retain,
tryRestoreFocus: tryRestoreFocus
};
var interactiveTagNames = {
input: true,
button: true,
textarea: true,
select: true,
option: true,
optgroup: true,
video: true,
audio: true
};
var isAnInteractiveElement = function isAnInteractiveElement(parent, current) {
if (current == null) {
return false;
}
var hasAnInteractiveTag = Boolean(interactiveTagNames[current.tagName.toLowerCase()]);
if (hasAnInteractiveTag) {
return true;
}
var attribute = current.getAttribute('contenteditable');
if (attribute === 'true' || attribute === '') {
return true;
}
if (current === parent) {
return false;
}
return isAnInteractiveElement(parent, current.parentElement);
};
var shouldAllowDraggingFromTarget = (function (event, props) {
if (props.canDragInteractiveElements) {
return true;
}
var target = event.target,
currentTarget = event.currentTarget;
if (!(target instanceof Element) || !(currentTarget instanceof Element)) {
return true;
}
return !isAnInteractiveElement(currentTarget, target);
});
var createScheduler = (function (callbacks) {
var memoizedMove = memoizeOne(function (x, y) {
var point = {
x: x,
y: y
};
callbacks.onMove(point);
});
var move = rafSchd(function (point) {
return memoizedMove(point.x, point.y);
});
var moveUp = rafSchd(callbacks.onMoveUp);
var moveDown = rafSchd(callbacks.onMoveDown);
var moveRight = rafSchd(callbacks.onMoveRight);
var moveLeft = rafSchd(callbacks.onMoveLeft);
var windowScrollMove = rafSchd(callbacks.onWindowScroll);
var cancel = function cancel() {
move.cancel();
moveUp.cancel();
moveDown.cancel();
moveRight.cancel();
moveLeft.cancel();
windowScrollMove.cancel();
};
return {
move: move,
moveUp: moveUp,
moveDown: moveDown,
moveRight: moveRight,
moveLeft: moveLeft,
windowScrollMove: windowScrollMove,
cancel: cancel
};
});
var sloppyClickThreshold = 5;
var isSloppyClickThresholdExceeded = (function (original, current) {
return Math.abs(current.x - original.x) >= sloppyClickThreshold || Math.abs(current.y - original.y) >= sloppyClickThreshold;
});
var tab = 9;
var enter = 13;
var escape = 27;
var space = 32;
var pageUp = 33;
var pageDown = 34;
var end = 35;
var home = 36;
var arrowLeft = 37;
var arrowUp = 38;
var arrowRight = 39;
var arrowDown = 40;
var _preventedKeys;
var preventedKeys = (_preventedKeys = {}, _preventedKeys[enter] = true, _preventedKeys[tab] = true, _preventedKeys);
var preventStandardKeyEvents = (function (event) {
if (preventedKeys[event.keyCode]) {
event.preventDefault();
}
});
var getOptions = function getOptions(shared, fromBinding) {
return _extends({}, shared, fromBinding);
};
var bindEvents = function bindEvents(el, bindings, sharedOptions) {
bindings.forEach(function (binding) {
var options = getOptions(sharedOptions, binding.options);
el.addEventListener(binding.eventName, binding.fn, options);
});
};
var unbindEvents = function unbindEvents(el, bindings, sharedOptions) {
bindings.forEach(function (binding) {
var options = getOptions(sharedOptions, binding.options);
el.removeEventListener(binding.eventName, binding.fn, options);
});
};
var sharedOptions = {
capture: true
};
var createPostDragEventPreventer = (function (getWindow) {
var isBound = false;
var bind = function bind() {
if (isBound) {
return;
}
isBound = true;
bindEvents(getWindow(), pointerEvents, sharedOptions);
};
var unbind = function unbind() {
if (!isBound) {
return;
}
isBound = false;
unbindEvents(getWindow(), pointerEvents, sharedOptions);
};
var pointerEvents = [{
eventName: 'click',
fn: function fn(event) {
event.preventDefault();
unbind();
}
}, {
eventName: 'mousedown',
fn: unbind
}, {
eventName: 'touchstart',
fn: unbind
}];
var preventNext = function preventNext() {
if (isBound) {
unbind();
}
bind();
};
var preventer = {
preventNext: preventNext,
abort: unbind
};
return preventer;
});
var createEventMarshal = (function () {
var isMouseDownHandled = false;
var handle = function handle() {
!!isMouseDownHandled ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot handle mouse down as it is already handled') : invariant(false) : void 0;
isMouseDownHandled = true;
};
var isHandled = function isHandled() {
return isMouseDownHandled;
};
var reset = function reset() {
isMouseDownHandled = false;
};
return {
handle: handle,
isHandled: isHandled,
reset: reset
};
});
var supportedEventName = function () {
var base = 'visibilitychange';
if (typeof document === 'undefined') {
return base;
}
var candidates = [base, "ms" + base, "webkit" + base, "moz" + base, "o" + base];
var supported = candidates.find(function (eventName) {
return "on" + eventName in document;
});
return supported || base;
}();
var primaryButton = 0;
var noop = function noop() {};
var mouseDownMarshal = createEventMarshal();
var createMouseSensor = (function (_ref) {
var callbacks = _ref.callbacks,
getWindow = _ref.getWindow,
canStartCapturing = _ref.canStartCapturing;
var state = {
isDragging: false,
pending: null
};
var setState = function setState(newState) {
state = newState;
};
var isDragging = function isDragging() {
return state.isDragging;
};
var isCapturing = function isCapturing() {
return Boolean(state.pending || state.isDragging);
};
var schedule = createScheduler(callbacks);
var postDragEventPreventer = createPostDragEventPreventer(getWindow);
var startDragging = function startDragging(fn) {
if (fn === void 0) {
fn = noop;
}
setState({
pending: null,
isDragging: true
});
fn();
};
var stopDragging = function stopDragging(fn, shouldBlockClick) {
if (fn === void 0) {
fn = noop;
}
if (shouldBlockClick === void 0) {
shouldBlockClick = true;
}
schedule.cancel();
unbindWindowEvents();
mouseDownMarshal.reset();
if (shouldBlockClick) {
postDragEventPreventer.preventNext();
}
setState({
isDragging: false,
pending: null
});
fn();
};
var startPendingDrag = function startPendingDrag(point) {
setState({
pending: point,
isDragging: false
});
bindWindowEvents();
};
var stopPendingDrag = function stopPendingDrag() {
stopDragging(noop, false);
};
var kill = function kill(fn) {
if (fn === void 0) {
fn = noop;
}
if (state.pending) {
stopPendingDrag();
return;
}
stopDragging(fn);
};
var unmount = function unmount() {
kill();
postDragEventPreventer.abort();
};
var cancel = function cancel() {
kill(callbacks.onCancel);
};
var windowBindings = [{
eventName: 'mousemove',
fn: function fn(event) {
var button = event.button,
clientX = event.clientX,
clientY = event.clientY;
if (button !== primaryButton) {
return;
}
var point = {
x: clientX,
y: clientY
};
if (state.isDragging) {
event.preventDefault();
schedule.move(point);
return;
}
if (!state.pending) {
kill();
process.env.NODE_ENV !== "production" ? invariant(false, 'Expected there to be a pending drag') : invariant(false);
}
if (!isSloppyClickThresholdExceeded(state.pending, point)) {
return;
}
event.preventDefault();
startDragging(function () {
return callbacks.onLift({
clientSelection: point,
autoScrollMode: 'FLUID'
});
});
}
}, {
eventName: 'mouseup',
fn: function fn(event) {
if (state.pending) {
stopPendingDrag();
return;
}
event.preventDefault();
stopDragging(callbacks.onDrop);
}
}, {
eventName: 'mousedown',
fn: function fn(event) {
if (state.isDragging) {
event.preventDefault();
}
stopDragging(callbacks.onCancel);
}
}, {
eventName: 'keydown',
fn: function fn(event) {
if (!state.isDragging) {
cancel();
return;
}
if (event.keyCode === escape) {
event.preventDefault();
cancel();
return;
}
preventStandardKeyEvents(event);
}
}, {
eventName: 'resize',
fn: cancel
}, {
eventName: 'scroll',
options: {
passive: true,
capture: false
},
fn: function fn() {
if (state.pending) {
stopPendingDrag();
return;
}
schedule.windowScrollMove();
}
}, {
eventName: 'webkitmouseforcechanged',
fn: function fn(event) {
if (event.webkitForce == null || MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN == null) {
if (process.env.NODE_ENV !== 'production') {
console.warn('handling a mouse force changed event when it is not supported');
}
return;
}
var forcePressThreshold = MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN;
var isForcePressing = event.webkitForce >= forcePressThreshold;
if (isForcePressing) {
cancel();
}
}
}, {
eventName: supportedEventName,
fn: cancel
}];
var bindWindowEvents = function bindWindowEvents() {
var win = getWindow();
bindEvents(win, windowBindings, {
capture: true
});
};
var unbindWindowEvents = function unbindWindowEvents() {
var win = getWindow();
unbindEvents(win, windowBindings, {
capture: true
});
};
var onMouseDown = function onMouseDown(event) {
if (mouseDownMarshal.isHandled()) {
return;
}
!!isCapturing() ? process.env.NODE_ENV !== "production" ? invariant(false, 'Should not be able to perform a mouse down while a drag or pending drag is occurring') : invariant(false) : void 0;
if (!canStartCapturing(event)) {
return;
}
if (event.button !== primaryButton) {
return;
}
if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {
return;
}
mouseDownMarshal.handle();
event.preventDefault();
var point = {
x: event.clientX,
y: event.clientY
};
startPendingDrag(point);
};
var sensor = {
onMouseDown: onMouseDown,
kill: kill,
isCapturing: isCapturing,
isDragging: isDragging,
unmount: unmount
};
return sensor;
});
var getBorderBoxCenterPosition = (function (el) {
return cssBoxModel.getRect(el.getBoundingClientRect()).center;
});
var _scrollJumpKeys;
var scrollJumpKeys = (_scrollJumpKeys = {}, _scrollJumpKeys[pageDown] = true, _scrollJumpKeys[pageUp] = true, _scrollJumpKeys[home] = true, _scrollJumpKeys[end] = true, _scrollJumpKeys);
var noop$1 = function noop() {};
var createKeyboardSensor = (function (_ref) {
var callbacks = _ref.callbacks,
getWindow = _ref.getWindow,
getDraggableRef = _ref.getDraggableRef,
canStartCapturing = _ref.canStartCapturing;
var state = {
isDragging: false
};
var setState = function setState(newState) {
state = newState;
};
var startDragging = function startDragging(fn) {
if (fn === void 0) {
fn = noop$1;
}
setState({
isDragging: true
});
bindWindowEvents();
fn();
};
var stopDragging = function stopDragging(fn) {
if (fn === void 0) {
fn = noop$1;
}
schedule.cancel();
unbindWindowEvents();
setState({
isDragging: false
});
fn();
};
var kill = function kill() {
return stopDragging();
};
var cancel = function cancel() {
stopDragging(callbacks.onCancel);
};
var isDragging = function isDragging() {
return state.isDragging;
};
var schedule = createScheduler(callbacks);
var onKeyDown = function onKeyDown(event) {
if (!isDragging()) {
if (event.defaultPrevented) {
return;
}
if (!canStartCapturing(event)) {
return;
}
if (event.keyCode !== space) {
return;
}
var ref = getDraggableRef();
!ref ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot start a keyboard drag without a draggable ref') : invariant(false) : void 0;
var center = getBorderBoxCenterPosition(ref);
event.preventDefault();
startDragging(function () {
return callbacks.onLift({
clientSelection: center,
autoScrollMode: 'JUMP'
});
});
return;
}
if (event.keyCode === escape) {
event.preventDefault();
cancel();
return;
}
if (event.keyCode === space) {
event.preventDefault();
stopDragging(callbacks.onDrop);
return;
}
if (event.keyCode === arrowDown) {
event.preventDefault();
schedule.moveDown();
return;
}
if (event.keyCode === arrowUp) {
event.preventDefault();
schedule.moveUp();
return;
}
if (event.keyCode === arrowRight) {
event.preventDefault();
schedule.moveRight();
return;
}
if (event.keyCode === arrowLeft) {
event.preventDefault();
schedule.moveLeft();
return;
}
if (scrollJumpKeys[event.keyCode]) {
event.preventDefault();
return;
}
preventStandardKeyEvents(event);
};
var windowBindings = [{
eventName: 'mousedown',
fn: cancel
}, {
eventName: 'mouseup',
fn: cancel
}, {
eventName: 'click',
fn: cancel
}, {
eventName: 'touchstart',
fn: cancel
}, {
eventName: 'resize',
fn: cancel
}, {
eventName: 'wheel',
fn: cancel
}, {
eventName: 'scroll',
options: {
capture: false
},
fn: callbacks.onWindowScroll
}, {
eventName: supportedEventName,
fn: cancel
}];
var bindWindowEvents = function bindWindowEvents() {
bindEvents(getWindow(), windowBindings, {
capture: true
});
};
var unbindWindowEvents = function unbindWindowEvents() {
unbindEvents(getWindow(), windowBindings, {
capture: true
});
};
var sensor = {
onKeyDown: onKeyDown,
kill: kill,
isDragging: isDragging,
isCapturing: isDragging,
unmount: kill
};
return sensor;
});
var timeForLongPress = 150;
var forcePressThreshold = 0.15;
var touchStartMarshal = createEventMarshal();
var noop$2 = function noop() {};
var webkitHack = function () {
var stub = {
preventTouchMove: noop$2,
releaseTouchMove: noop$2
};
if (typeof window === 'undefined') {
return stub;
}
if (!('ontouchstart' in window)) {
return stub;
}
var isBlocking = false;
window.addEventListener('touchmove', function (event) {
if (!isBlocking) {
return;
}
if (event.defaultPrevented) {
return;
}
event.preventDefault();
}, {
passive: false,
capture: false
});
var preventTouchMove = function preventTouchMove() {
isBlocking = true;
};
var releaseTouchMove = function releaseTouchMove() {
isBlocking = false;
};
return {
preventTouchMove: preventTouchMove,
releaseTouchMove: releaseTouchMove
};
}();
var initial = {
isDragging: false,
pending: null,
hasMoved: false,
longPressTimerId: null
};
var createTouchSensor = (function (_ref) {
var callbacks = _ref.callbacks,
getWindow = _ref.getWindow,
canStartCapturing = _ref.canStartCapturing;
var state = initial;
var setState = function setState(partial) {
state = _extends({}, state, partial);
};
var isDragging = function isDragging() {
return state.isDragging;
};
var isCapturing = function isCapturing() {
return Boolean(state.pending || state.isDragging || state.longPressTimerId);
};
var schedule = createScheduler(callbacks);
var postDragEventPreventer = createPostDragEventPreventer(getWindow);
var startDragging = function startDragging() {
var pending = state.pending;
if (!pending) {
kill();
process.env.NODE_ENV !== "production" ? invariant(false, 'cannot start a touch drag without a pending position') : invariant(false);
}
setState({
isDragging: true,
hasMoved: false,
pending: null,
longPressTimerId: null
});
callbacks.onLift({
clientSelection: pending,
autoScrollMode: 'FLUID'
});
};
var stopDragging = function stopDragging(fn) {
if (fn === void 0) {
fn = noop$2;
}
schedule.cancel();
touchStartMarshal.reset();
webkitHack.releaseTouchMove();
unbindWindowEvents();
postDragEventPreventer.preventNext();
setState(initial);
fn();
};
var startPendingDrag = function startPendingDrag(event) {
var touch = event.touches[0];
var clientX = touch.clientX,
clientY = touch.clientY;
var point = {
x: clientX,
y: clientY
};
var longPressTimerId = setTimeout(startDragging, timeForLongPress);
setState({
longPressTimerId: longPressTimerId,
pending: point,
isDragging: false,
hasMoved: false
});
bindWindowEvents();
};
var stopPendingDrag = function stopPendingDrag() {
if (state.longPressTimerId) {
clearTimeout(state.longPressTimerId);
}
schedule.cancel();
touchStartMarshal.reset();
webkitHack.releaseTouchMove();
unbindWindowEvents();
setState(initial);
};
var kill = function kill(fn) {
if (fn === void 0) {
fn = noop$2;
}
if (state.pending) {
stopPendingDrag();
return;
}
stopDragging(fn);
};
var unmount = function unmount() {
kill();
postDragEventPreventer.abort();
};
var cancel = function cancel() {
kill(callbacks.onCancel);
};
var windowBindings = [{
eventName: 'touchmove',
options: {
passive: false
},
fn: function fn(event) {
if (!state.isDragging) {
stopPendingDrag();
return;
}
if (!state.hasMoved) {
setState({
hasMoved: true
});
}
var _event$touches$ = event.touches[0],
clientX = _event$touches$.clientX,
clientY = _event$touches$.clientY;
var point = {
x: clientX,
y: clientY
};
event.preventDefault();
schedule.move(point);
}
}, {
eventName: 'touchend',
fn: function fn(event) {
if (!state.isDragging) {
stopPendingDrag();
return;
}
event.preventDefault();
stopDragging(callbacks.onDrop);
}
}, {
eventName: 'touchcancel',
fn: function fn(event) {
if (!state.isDragging) {
stopPendingDrag();
return;
}
event.preventDefault();
stopDragging(callbacks.onCancel);
}
}, {
eventName: 'touchstart',
fn: cancel
}, {
eventName: 'orientationchange',
fn: cancel
}, {
eventName: 'resize',
fn: cancel
}, {
eventName: 'scroll',
options: {
passive: true,
capture: false
},
fn: function fn() {
if (state.pending) {
stopPendingDrag();
return;
}
schedule.windowScrollMove();
}
}, {
eventName: 'contextmenu',
fn: function fn(event) {
event.preventDefault();
}
}, {
eventName: 'keydown',
fn: function fn(event) {
if (!state.isDragging) {
cancel();
return;
}
if (event.keyCode === escape) {
event.preventDefault();
}
cancel();
}
}, {
eventName: 'touchforcechange',
fn: function fn(event) {
if (state.hasMoved) {
event.preventDefault();
return;
}
var touch = event.touches[0];
if (touch.force >= forcePressThreshold) {
cancel();
}
}
}, {
eventName: supportedEventName,
fn: cancel
}];
var bindWindowEvents = function bindWindowEvents() {
bindEvents(getWindow(), windowBindings, {
capture: true
});
};
var unbindWindowEvents = function unbindWindowEvents() {
unbindEvents(getWindow(), windowBindings, {
capture: true
});
};
var onTouchStart = function onTouchStart(event) {
if (touchStartMarshal.isHandled()) {
return;
}
!!isCapturing() ? process.env.NODE_ENV !== "production" ? invariant(false, 'Should not be able to perform a touch start while a drag or pending drag is occurring') : invariant(false) : void 0;
if (!canStartCapturing(event)) {
return;
}
touchStartMarshal.handle();
webkitHack.preventTouchMove();
startPendingDrag(event);
};
var sensor = {
onTouchStart: onTouchStart,
kill: kill,
isCapturing: isCapturing,
isDragging: isDragging,
unmount: unmount
};
return sensor;
});
var _DragHandle$contextTy;
var preventHtml5Dnd = function preventHtml5Dnd(event) {
event.preventDefault();
};
var DragHandle = function (_Component) {
_inheritsLoose(DragHandle, _Component);
function DragHandle(props, context) {
var _this;
_this = _Component.call(this, props, context) || this;
_this.mouseSensor = void 0;
_this.keyboardSensor = void 0;
_this.touchSensor = void 0;
_this.sensors = void 0;
_this.styleContext = void 0;
_this.canLift = void 0;
_this.isFocused = false;
_this.lastDraggableRef = void 0;
_this.onFocus = function () {
_this.isFocused = true;
};
_this.onBlur = function () {
_this.isFocused = false;
};
_this.onKeyDown = function (event) {
if (_this.mouseSensor.isCapturing() || _this.touchSensor.isCapturing()) {
return;
}
_this.keyboardSensor.onKeyDown(event);
};
_this.onMouseDown = function (event) {
if (_this.keyboardSensor.isCapturing() || _this.mouseSensor.isCapturing()) {
return;
}
_this.mouseSensor.onMouseDown(event);
};
_this.onTouchStart = function (event) {
if (_this.mouseSensor.isCapturing() || _this.keyboardSensor.isCapturing()) {
return;
}
_this.touchSensor.onTouchStart(event);
};
_this.canStartCapturing = function (event) {
if (_this.isAnySensorCapturing()) {
return false;
}
if (!_this.canLift(_this.props.draggableId)) {
return false;
}
return shouldAllowDraggingFromTarget(event, _this.props);
};
_this.isAnySensorCapturing = function () {
return _this.sensors.some(function (sensor) {
return sensor.isCapturing();
});
};
_this.getProvided = memoizeOne(function (isEnabled) {
if (!isEnabled) {
return null;
}
var provided = {
onMouseDown: _this.onMouseDown,
onKeyDown: _this.onKeyDown,
onTouchStart: _this.onTouchStart,
onFocus: _this.onFocus,
onBlur: _this.onBlur,
tabIndex: 0,
'data-react-beautiful-dnd-drag-handle': _this.styleContext,
'aria-roledescription': 'Draggable item. Press space bar to lift',
draggable: false,
onDragStart: preventHtml5Dnd
};
return provided;
});
var getWindow = function getWindow() {
return getWindowFromRef(_this.props.getDraggableRef());
};
var args = {
callbacks: _this.props.callbacks,
getDraggableRef: _this.props.getDraggableRef,
getWindow: getWindow,
canStartCapturing: _this.canStartCapturing
};
_this.mouseSensor = createMouseSensor(args);
_this.keyboardSensor = createKeyboardSensor(args);
_this.touchSensor = createTouchSensor(args);
_this.sensors = [_this.mouseSensor, _this.keyboardSensor, _this.touchSensor];
_this.styleContext = context[styleContextKey];
_this.canLift = context[canLiftContextKey];
return _this;
}
var _proto = DragHandle.prototype;
_proto.componentDidMount = function componentDidMount() {
var draggableRef = this.props.getDraggableRef();
this.lastDraggableRef = draggableRef;
!draggableRef ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot get draggable ref from drag handle') : invariant(false) : void 0;
if (!this.props.isEnabled) {
return;
}
var dragHandleRef = getDragHandleRef(draggableRef);
retainer.tryRestoreFocus(this.props.draggableId, dragHandleRef);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this2 = this;
var ref = this.props.getDraggableRef();
if (ref !== this.lastDraggableRef) {
this.lastDraggableRef = ref;
if (!ref || !this.isFocused) {
return;
}
if (!this.props.isEnabled) {
return;
}
getDragHandleRef(ref).focus();
}
var isCapturing = this.isAnySensorCapturing();
if (!isCapturing) {
return;
}
var isDragStopping = prevProps.isDragging && !this.props.isDragging;
if (isDragStopping) {
this.sensors.forEach(function (sensor) {
if (sensor.isCapturing()) {
sensor.kill();
}
});
}
if (this.props.isEnabled) {
return;
}
this.sensors.forEach(function (sensor) {
if (!sensor.isCapturing()) {
return;
}
var wasDragging = sensor.isDragging();
sensor.kill();
if (wasDragging) {
if (process.env.NODE_ENV !== 'production') {
console.warn('You have disabled dragging on a Draggable while it was dragging. The drag has been cancelled');
}
_this2.props.callbacks.onCancel();
}
});
};
_proto.componentWillUnmount = function componentWillUnmount() {
var _this3 = this;
this.sensors.forEach(function (sensor) {
var wasDragging = sensor.isDragging();
sensor.unmount();
if (wasDragging) {
_this3.props.callbacks.onCancel();
}
});
var shouldRetainFocus = function () {
if (!_this3.props.isEnabled) {
return false;
}
if (!_this3.isFocused) {
return false;
}
return _this3.props.isDragging || _this3.props.isDropAnimating;
}();
if (shouldRetainFocus) {
retainer.retain(this.props.draggableId);
}
};
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
isEnabled = _this$props.isEnabled;
return children(this.getProvided(isEnabled));
};
return DragHandle;
}(React.Component);
DragHandle.contextTypes = (_DragHandle$contextTy = {}, _DragHandle$contextTy[styleContextKey] = PropTypes.string.isRequired, _DragHandle$contextTy[canLiftContextKey] = PropTypes.func.isRequired, _DragHandle$contextTy);
var getWindowScroll = (function () {
return {
x: window.pageXOffset,
y: window.pageYOffset
};
});
var getViewport = (function () {
var scroll = getWindowScroll();
var top = scroll.y;
var left = scroll.x;
var doc = document.documentElement;
!doc ? process.env.NODE_ENV !== "production" ? invariant(false, 'Could not find document.documentElement') : invariant(false) : void 0;
var width = doc.clientWidth;
var height = doc.clientHeight;
var right = left + width;
var bottom = top + height;
var frame = cssBoxModel.getRect({
top: top,
left: left,
right: right,
bottom: bottom
});
var maxScroll = getMaxScroll({
scrollHeight: doc.scrollHeight,
scrollWidth: doc.scrollWidth,
width: frame.width,
height: frame.height
});
var viewport = {
frame: frame,
scroll: {
initial: scroll,
current: scroll,
max: maxScroll,
diff: {
value: origin,
displacement: origin
}
}
};
return viewport;
});
var _Draggable$contextTyp;
var zIndexOptions = {
dragging: 5000,
dropAnimating: 4500
};
var getTranslate = function getTranslate(offset) {
if (isEqual(offset, origin)) {
return null;
}
return "translate(" + offset.x + "px, " + offset.y + "px)";
};
var getSpeed$1 = function getSpeed(isDragging, shouldAnimateDragMovement, isDropAnimating) {
if (isDropAnimating) {
return 'STANDARD';
}
if (isDragging && shouldAnimateDragMovement) {
return 'FAST';
}
return 'INSTANT';
};
var Draggable = function (_Component) {
_inheritsLoose(Draggable, _Component);
function Draggable(props, context) {
var _this;
_this = _Component.call(this, props, context) || this;
_this.callbacks = void 0;
_this.styleContext = void 0;
_this.ref = null;
_this.onMoveEnd = function () {
if (_this.props.isDropAnimating) {
_this.props.dropAnimationFinished();
}
};
_this.onLift = function (options) {
start('LIFT');
var ref = _this.ref;
!ref ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
!!_this.props.isDragDisabled ? process.env.NODE_ENV !== "production" ? invariant(false, 'Cannot lift a Draggable when it is disabled') : invariant(false) : void 0;
var clientSelection = options.clientSelection,
autoScrollMode = options.autoScrollMode;
var _this$props = _this.props,
lift = _this$props.lift,
draggableId = _this$props.draggableId;
var client = {
selection: clientSelection,
borderBoxCenter: getBorderBoxCenterPosition(ref),
offset: origin
};
lift({
id: draggableId,
client: client,
autoScrollMode: autoScrollMode,
viewport: getViewport()
});
finish('LIFT');
};
_this.setRef = function (ref) {
if (ref === null) {
return;
}
if (ref === _this.ref) {
return;
}
_this.ref = ref;
throwIfRefIsInvalid(ref);
};
_this.getDraggableRef = function () {
return _this.ref;
};
_this.getDraggingStyle = memoizeOne(function (change, dimension, isDropAnimating) {
var box = dimension.client;
var style = {
position: 'fixed',
top: box.marginBox.top,
left: box.marginBox.left,
boxSizing: 'border-box',
width: box.borderBox.width,
height: box.borderBox.height,
transition: 'none',
zIndex: isDropAnimating ? zIndexOptions.dropAnimating : zIndexOptions.dragging,
transform: getTranslate(change),
pointerEvents: 'none'
};
return style;
});
_this.getNotDraggingStyle = memoizeOne(function (current, shouldAnimateDisplacement) {
var style = {
transform: getTranslate(current),
transition: shouldAnimateDisplacement ? null : 'none'
};
return style;
});
_this.getProvided = memoizeOne(function (change, isDragging, isDropAnimating, shouldAnimateDisplacement, dimension, dragHandleProps) {
var useDraggingStyle = isDragging || isDropAnimating;
var draggableStyle = function () {
if (!useDraggingStyle) {
return _this.getNotDraggingStyle(change, shouldAnimateDisplacement);
}
!dimension ? process.env.NODE_ENV !== "production" ? invariant(false, 'draggable dimension required for dragging') : invariant(false) : void 0;
return _this.getDraggingStyle(change, dimension, isDropAnimating);
}();
var provided = {
innerRef: _this.setRef,
draggableProps: {
'data-react-beautiful-dnd-draggable': _this.styleContext,
style: draggableStyle
},
dragHandleProps: dragHandleProps
};
return provided;
});
_this.getSnapshot = memoizeOne(function (isDragging, isDropAnimating, draggingOver) {
return {
isDragging: isDragging || isDropAnimating,
isDropAnimating: isDropAnimating,
draggingOver: draggingOver
};
});
_this.renderChildren = function (change, dragHandleProps) {
var _this$props2 = _this.props,
isDragging = _this$props2.isDragging,
isDropAnimating = _this$props2.isDropAnimating,
dimension = _this$props2.dimension,
draggingOver = _this$props2.draggingOver,
shouldAnimateDisplacement = _this$props2.shouldAnimateDisplacement,
children = _this$props2.children;
var child = children(_this.getProvided(change, isDragging, isDropAnimating, shouldAnimateDisplacement, dimension, dragHandleProps), _this.getSnapshot(isDragging, isDropAnimating, draggingOver));
var isDraggingOrDropping = isDragging || isDropAnimating;
var placeholder = function () {
if (!isDraggingOrDropping) {
return null;
}
!dimension ? process.env.NODE_ENV !== "production" ? invariant(false, 'Draggable: Dimension is required for dragging') : invariant(false) : void 0;
return React__default.createElement(Placeholder, {
placeholder: dimension.placeholder
});
}();
return React__default.createElement(React.Fragment, null, child, placeholder);
};
var callbacks = {
onLift: _this.onLift,
onMove: function onMove(clientSelection) {
return props.move({
client: clientSelection,
shouldAnimate: false
});
},
onDrop: function onDrop() {
return props.drop({
reason: 'DROP'
});
},
onCancel: function onCancel() {
return props.drop({
reason: 'CANCEL'
});
},
onMoveUp: props.moveUp,
onMoveDown: props.moveDown,
onMoveRight: props.moveRight,
onMoveLeft: props.moveLeft,
onWindowScroll: function onWindowScroll() {
return props.moveByWindowScroll({
scroll: getWindowScroll()
});
}
};
_this.callbacks = callbacks;
_this.styleContext = context[styleContextKey];
return _this;
}
var _proto = Draggable.prototype;
_proto.componentWillUnmount = function componentWillUnmount() {
this.ref = null;
};
_proto.render = function render() {
var _this2 = this;
var _this$props3 = this.props,
draggableId = _this$props3.draggableId,
index = _this$props3.index,
offset = _this$props3.offset,
isDragging = _this$props3.isDragging,
isDropAnimating = _this$props3.isDropAnimating,
isDragDisabled = _this$props3.isDragDisabled,
shouldAnimateDragMovement = _this$props3.shouldAnimateDragMovement,
disableInteractiveElementBlocking = _this$props3.disableInteractiveElementBlocking;
var droppableId = this.context[droppableIdKey];
var type = this.context[droppableTypeKey];
var speed = getSpeed$1(isDragging, shouldAnimateDragMovement, isDropAnimating);
return React__default.createElement(DraggableDimensionPublisher, {
key: draggableId,
draggableId: draggableId,
droppableId: droppableId,
type: type,
index: index,
getDraggableRef: this.getDraggableRef
}, React__default.createElement(Moveable, {
speed: speed,
destination: offset,
onMoveEnd: this.onMoveEnd
}, function (change) {
return React__default.createElement(DragHandle, {
draggableId: draggableId,
isDragging: isDragging,
isDropAnimating: isDropAnimating,
isEnabled: !isDragDisabled,
callbacks: _this2.callbacks,
getDraggableRef: _this2.getDraggableRef,
canDragInteractiveElements: disableInteractiveElementBlocking
}, function (dragHandleProps) {
return _this2.renderChildren(change, dragHandleProps);
});
}));
};
return Draggable;
}(React.Component);
Draggable.contextTypes = (_Draggable$contextTyp = {}, _Draggable$contextTyp[droppableIdKey] = PropTypes.string.isRequired, _Draggable$contextTyp[droppableTypeKey] = PropTypes.string.isRequired, _Draggable$contextTyp[styleContextKey] = PropTypes.string.isRequired, _Draggable$contextTyp);
var defaultMapProps = {
isDropAnimating: false,
isDragging: false,
offset: origin,
shouldAnimateDragMovement: false,
shouldAnimateDisplacement: true,
dimension: null,
draggingOver: null
};
var makeMapStateToProps$1 = function makeMapStateToProps() {
var memoizedOffset = memoizeOne(function (x, y) {
return {
x: x,
y: y
};
});
var getNotDraggingProps = memoizeOne(function (offset, shouldAnimateDisplacement) {
return {
isDropAnimating: false,
isDragging: false,
offset: offset,
shouldAnimateDisplacement: shouldAnimateDisplacement,
shouldAnimateDragMovement: false,
dimension: null,
draggingOver: null
};
});
var getDraggingProps = memoizeOne(function (offset, shouldAnimateDragMovement, dimension, draggingOver) {
return {
isDragging: true,
isDropAnimating: false,
shouldAnimateDisplacement: false,
offset: offset,
shouldAnimateDragMovement: shouldAnimateDragMovement,
dimension: dimension,
draggingOver: draggingOver
};
});
var getOutOfTheWayMovement = function getOutOfTheWayMovement(id, movement) {
var map = getDisplacementMap(movement.displaced);
var displacement = map[id];
if (!displacement) {
return null;
}
if (!displacement.isVisible) {
return null;
}
var amount = movement.isBeyondStartPosition ? negate(movement.amount) : movement.amount;
return getNotDraggingProps(memoizedOffset(amount.x, amount.y), displacement.shouldAnimate);
};
var draggingSelector = function draggingSelector(state, ownProps) {
if (state.isDragging) {
if (state.critical.draggable.id !== ownProps.draggableId) {
return null;
}
var offset = state.current.client.offset;
var dimension = state.dimensions.draggables[ownProps.draggableId];
var shouldAnimateDragMovement = state.shouldAnimate;
var draggingOver = state.impact.destination ? state.impact.destination.droppableId : null;
return getDraggingProps(memoizedOffset(offset.x, offset.y), shouldAnimateDragMovement, dimension, draggingOver);
}
if (state.phase === 'DROP_ANIMATING') {
var pending = state.pending;
if (pending.result.draggableId !== ownProps.draggableId) {
return null;
}
var _draggingOver = pending.result.destination ? pending.result.destination.droppableId : null;
return {
isDragging: false,
isDropAnimating: true,
offset: pending.newHomeOffset,
dimension: state.dimensions.draggables[ownProps.draggableId],
draggingOver: _draggingOver,
shouldAnimateDragMovement: false,
shouldAnimateDisplacement: false
};
}
return null;
};
var movingOutOfTheWaySelector = function movingOutOfTheWaySelector(state, ownProps) {
if (state.isDragging) {
if (state.critical.draggable.id === ownProps.draggableId) {
return null;
}
return getOutOfTheWayMovement(ownProps.draggableId, state.impact.movement);
}
if (state.phase === 'DROP_ANIMATING') {
if (state.pending.result.draggableId === ownProps.draggableId) {
return null;
}
return getOutOfTheWayMovement(ownProps.draggableId, state.pending.impact.movement);
}
return null;
};
var selector = function selector(state, ownProps) {
var dragging = draggingSelector(state, ownProps);
if (dragging) {
return dragging;
}
var movingOutOfTheWay = movingOutOfTheWaySelector(state, ownProps);
if (movingOutOfTheWay) {
return movingOutOfTheWay;
}
return defaultMapProps;
};
return selector;
};
var mapDispatchToProps = {
lift: lift,
move: move,
moveUp: moveUp,
moveDown: moveDown,
moveLeft: moveLeft,
moveRight: moveRight,
moveByWindowScroll: moveByWindowScroll,
drop: drop,
dropAnimationFinished: dropAnimationFinished
};
var ConnectedDraggable = reactRedux.connect(makeMapStateToProps$1, mapDispatchToProps, null, {
storeKey: storeKey,
pure: true,
areStatePropsEqual: isStrictEqual
})(Draggable);
ConnectedDraggable.defaultProps = {
isDragDisabled: false,
disableInteractiveElementBlocking: false
};
exports.DragDropContext = DragDropContext;
exports.Droppable = connectedDroppable;
exports.Draggable = ConnectedDraggable;
exports.resetServerContext = resetServerContext;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
var _Object$assign = __webpack_require__(158);
function _extends() {
module.exports = _extends = _Object$assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
module.exports = _extends;
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(159);
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(160);
module.exports = __webpack_require__(163).Object.assign;
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(161);
$export($export.S + $export.F, 'Object', { assign: __webpack_require__(177) });
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(162);
var core = __webpack_require__(163);
var ctx = __webpack_require__(164);
var hide = __webpack_require__(166);
var has = __webpack_require__(176);
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var IS_WRAP = type & $export.W;
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE];
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
var key, own, out;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if (own && has(exports, key)) continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function (C) {
var F = function (a, b, c) {
if (this instanceof C) {
switch (arguments.length) {
case 0: return new C();
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if (IS_PROTO) {
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/* 162 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/* 163 */
/***/ (function(module, exports) {
var core = module.exports = { version: '2.6.5' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(165);
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/* 165 */
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(167);
var createDesc = __webpack_require__(175);
module.exports = __webpack_require__(171) ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(168);
var IE8_DOM_DEFINE = __webpack_require__(170);
var toPrimitive = __webpack_require__(174);
var dP = Object.defineProperty;
exports.f = __webpack_require__(171) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(169);
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/* 169 */
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(171) && !__webpack_require__(172)(function () {
return Object.defineProperty(__webpack_require__(173)('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(172)(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 172 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(169);
var document = __webpack_require__(162).document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(169);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/* 175 */
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/* 176 */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(178);
var gOPS = __webpack_require__(193);
var pIE = __webpack_require__(194);
var toObject = __webpack_require__(195);
var IObject = __webpack_require__(181);
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(172)(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
} return T;
} : $assign;
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(179);
var enumBugKeys = __webpack_require__(192);
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(176);
var toIObject = __webpack_require__(180);
var arrayIndexOf = __webpack_require__(184)(false);
var IE_PROTO = __webpack_require__(188)('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(181);
var defined = __webpack_require__(183);
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(182);
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/* 182 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/* 183 */
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(180);
var toLength = __webpack_require__(185);
var toAbsoluteIndex = __webpack_require__(187);
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/* 185 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(186);
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/* 186 */
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(186);
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(189)('keys');
var uid = __webpack_require__(191);
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__(163);
var global = __webpack_require__(162);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: core.version,
mode: __webpack_require__(190) ? 'pure' : 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/* 190 */
/***/ (function(module, exports) {
module.exports = true;
/***/ }),
/* 191 */
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/* 192 */
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/* 193 */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/* 194 */
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/* 195 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(183);
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
var isProduction = process.env.NODE_ENV === 'production';
var prefix = 'Invariant failed';
function invariant(condition, message) {
if (condition) {
return;
}
if (isProduction) {
throw new Error(prefix);
} else {
throw new Error(prefix + ": " + (message || ''));
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var invariant = _interopDefault(__webpack_require__(196));
var getRect = function getRect(_ref) {
var top = _ref.top,
right = _ref.right,
bottom = _ref.bottom,
left = _ref.left;
var width = right - left;
var height = bottom - top;
var rect = {
top: top,
right: right,
bottom: bottom,
left: left,
width: width,
height: height,
x: left,
y: top,
center: {
x: (right + left) / 2,
y: (bottom + top) / 2
}
};
return rect;
};
var expand = function expand(target, expandBy) {
return {
top: target.top - expandBy.top,
left: target.left - expandBy.left,
bottom: target.bottom + expandBy.bottom,
right: target.right + expandBy.right
};
};
var shrink = function shrink(target, shrinkBy) {
return {
top: target.top + shrinkBy.top,
left: target.left + shrinkBy.left,
bottom: target.bottom - shrinkBy.bottom,
right: target.right - shrinkBy.right
};
};
var shift = function shift(target, shiftBy) {
return {
top: target.top + shiftBy.y,
left: target.left + shiftBy.x,
bottom: target.bottom + shiftBy.y,
right: target.right + shiftBy.x
};
};
var noSpacing = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
var createBox = function createBox(_ref2) {
var borderBox = _ref2.borderBox,
_ref2$margin = _ref2.margin,
margin = _ref2$margin === void 0 ? noSpacing : _ref2$margin,
_ref2$border = _ref2.border,
border = _ref2$border === void 0 ? noSpacing : _ref2$border,
_ref2$padding = _ref2.padding,
padding = _ref2$padding === void 0 ? noSpacing : _ref2$padding;
var marginBox = getRect(expand(borderBox, margin));
var paddingBox = getRect(shrink(borderBox, border));
var contentBox = getRect(shrink(paddingBox, padding));
return {
marginBox: marginBox,
borderBox: getRect(borderBox),
paddingBox: paddingBox,
contentBox: contentBox,
margin: margin,
border: border,
padding: padding
};
};
var parse = function parse(raw) {
var value = raw.slice(0, -2);
var suffix = raw.slice(-2);
if (suffix !== 'px') {
return 0;
}
var result = Number(value);
!!isNaN(result) ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not parse value [raw: " + raw + ", without suffix: " + value + "]") : invariant(false) : void 0;
return result;
};
var getWindowScroll = function getWindowScroll() {
return {
x: window.pageXOffset,
y: window.pageYOffset
};
};
var offset = function offset(original, change) {
var borderBox = original.borderBox,
border = original.border,
margin = original.margin,
padding = original.padding;
var shifted = shift(borderBox, change);
return createBox({
borderBox: shifted,
border: border,
margin: margin,
padding: padding
});
};
var withScroll = function withScroll(original, scroll) {
if (scroll === void 0) {
scroll = getWindowScroll();
}
return offset(original, scroll);
};
var calculateBox = function calculateBox(borderBox, styles) {
var margin = {
top: parse(styles.marginTop),
right: parse(styles.marginRight),
bottom: parse(styles.marginBottom),
left: parse(styles.marginLeft)
};
var padding = {
top: parse(styles.paddingTop),
right: parse(styles.paddingRight),
bottom: parse(styles.paddingBottom),
left: parse(styles.paddingLeft)
};
var border = {
top: parse(styles.borderTopWidth),
right: parse(styles.borderRightWidth),
bottom: parse(styles.borderBottomWidth),
left: parse(styles.borderLeftWidth)
};
return createBox({
borderBox: borderBox,
margin: margin,
padding: padding,
border: border
});
};
var getBox = function getBox(el) {
var borderBox = el.getBoundingClientRect();
var styles = window.getComputedStyle(el);
return calculateBox(borderBox, styles);
};
exports.calculateBox = calculateBox;
exports.createBox = createBox;
exports.expand = expand;
exports.getBox = getBox;
exports.getRect = getRect;
exports.offset = offset;
exports.shrink = shrink;
exports.withScroll = withScroll;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(199);
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(200);
module.exports = __webpack_require__(163).Object.keys;
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(195);
var $keys = __webpack_require__(178);
__webpack_require__(201)('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(161);
var core = __webpack_require__(163);
var fails = __webpack_require__(172);
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
/***/ }),
/* 202 */
/***/ (function(module, exports) {
'use strict';
var simpleIsEqual = function simpleIsEqual(a, b) {
return a === b;
};
function index (resultFn, isEqual) {
if (isEqual === void 0) {
isEqual = simpleIsEqual;
}
var lastThis;
var lastArgs = [];
var lastResult;
var calledOnce = false;
var isNewArgEqualToLast = function isNewArgEqualToLast(newArg, index) {
return isEqual(newArg, lastArgs[index]);
};
var result = function result() {
for (var _len = arguments.length, newArgs = new Array(_len), _key = 0; _key < _len; _key++) {
newArgs[_key] = arguments[_key];
}
if (calledOnce && lastThis === this && newArgs.length === lastArgs.length && newArgs.every(isNewArgEqualToLast)) {
return lastResult;
}
lastResult = resultFn.apply(this, newArgs);
calledOnce = true;
lastThis = this;
lastArgs = newArgs;
return lastResult;
};
return result;
}
module.exports = index;
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var $$observable = _interopDefault(__webpack_require__(204));
/**
* These are private action types reserved by Redux.
* For any unknown actions, you must return the current state.
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
var randomString = function randomString() {
return Math.random().toString(36).substring(7).split('').join('.');
};
var ActionTypes = {
INIT: "@@redux/INIT" + randomString(),
REPLACE: "@@redux/REPLACE" + randomString(),
PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
}
};
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false;
var proto = obj;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(obj) === proto;
}
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [preloadedState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} [enhancer] The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
function createStore(reducer, preloadedState, enhancer) {
var _ref2;
if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function');
}
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState;
preloadedState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.');
}
return enhancer(createStore)(reducer, preloadedState);
}
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.');
}
var currentReducer = reducer;
var currentState = preloadedState;
var currentListeners = [];
var nextListeners = currentListeners;
var isDispatching = false;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
if (isDispatching) {
throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
}
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* You may call `dispatch()` from a change listener, with the following
* caveats:
*
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
* If you subscribe or unsubscribe while the listeners are being invoked, this
* will not have any effect on the `dispatch()` that is currently in progress.
* However, the next `dispatch()` call, whether nested or not, will use a more
* recent snapshot of the subscription list.
*
* 2. The listener should not expect to see all state changes, as the state
* might have been updated multiple times during a nested `dispatch()` before
* the listener is called. It is, however, guaranteed that all subscribers
* registered before the `dispatch()` started will be called with the latest
* state by the time it exits.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected the listener to be a function.');
}
if (isDispatching) {
throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.');
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function unsubscribe() {
if (!isSubscribed) {
return;
}
if (isDispatching) {
throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.');
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
};
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must have
* a `type` property which may not be `undefined`. It is a good idea to use
* string constants for action types.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action) {
if (!isPlainObject(action)) {
throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
}
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
}
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
listener();
}
return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer) {
if (typeof nextReducer !== 'function') {
throw new Error('Expected the nextReducer to be a function.');
}
currentReducer = nextReducer;
dispatch({
type: ActionTypes.REPLACE
});
}
/**
* Interoperability point for observable/reactive libraries.
* @returns {observable} A minimal observable of state changes.
* For more information, see the observable proposal:
* https://github.com/tc39/proposal-observable
*/
function observable() {
var _ref;
var outerSubscribe = subscribe;
return _ref = {
/**
* The minimal observable subscription method.
* @param {Object} observer Any object that can be used as an observer.
* The observer object should have a `next` method.
* @returns {subscription} An object with an `unsubscribe` method that can
* be used to unsubscribe the observable from the store, and prevent further
* emission of values from the observable.
*/
subscribe: function subscribe(observer) {
if (typeof observer !== 'object' || observer === null) {
throw new TypeError('Expected the observer to be an object.');
}
function observeState() {
if (observer.next) {
observer.next(getState());
}
}
observeState();
var unsubscribe = outerSubscribe(observeState);
return {
unsubscribe: unsubscribe
};
}
}, _ref[$$observable] = function () {
return this;
}, _ref;
} // When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({
type: ActionTypes.INIT
});
return _ref2 = {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
replaceReducer: replaceReducer
}, _ref2[$$observable] = observable, _ref2;
}
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that if you enable
// "break on all exceptions" in your console,
// it would pause the execution at this line.
throw new Error(message);
} catch (e) {} // eslint-disable-line no-empty
}
function getUndefinedStateErrorMessage(key, action) {
var actionType = action && action.type;
var actionDescription = actionType && "action \"" + String(actionType) + "\"" || 'an action';
return "Given " + actionDescription + ", reducer \"" + key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined.";
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
var reducerKeys = Object.keys(reducers);
var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!isPlainObject(inputState)) {
return "The " + argumentName + " has unexpected type of \"" + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
});
unexpectedKeys.forEach(function (key) {
unexpectedKeyCache[key] = true;
});
if (action && action.type === ActionTypes.REPLACE) return;
if (unexpectedKeys.length > 0) {
return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored.");
}
}
function assertReducerShape(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, {
type: ActionTypes.INIT
});
if (typeof initialState === 'undefined') {
throw new Error("Reducer \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
}
if (typeof reducer(undefined, {
type: ActionTypes.PROBE_UNKNOWN_ACTION()
}) === 'undefined') {
throw new Error("Reducer \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle " + ActionTypes.INIT + " or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var reducerKeys = Object.keys(reducers);
var finalReducers = {};
for (var i = 0; i < reducerKeys.length; i++) {
var key = reducerKeys[i];
if (process.env.NODE_ENV !== 'production') {
if (typeof reducers[key] === 'undefined') {
warning("No reducer provided for key \"" + key + "\"");
}
}
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key];
}
}
var finalReducerKeys = Object.keys(finalReducers);
var unexpectedKeyCache;
if (process.env.NODE_ENV !== 'production') {
unexpectedKeyCache = {};
}
var shapeAssertionError;
try {
assertReducerShape(finalReducers);
} catch (e) {
shapeAssertionError = e;
}
return function combination(state, action) {
if (state === void 0) {
state = {};
}
if (shapeAssertionError) {
throw shapeAssertionError;
}
if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
if (warningMessage) {
warning(warningMessage);
}
}
var hasChanged = false;
var nextState = {};
for (var _i = 0; _i < finalReducerKeys.length; _i++) {
var _key = finalReducerKeys[_i];
var reducer = finalReducers[_key];
var previousStateForKey = state[_key];
var nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(_key, action);
throw new Error(errorMessage);
}
nextState[_key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
return hasChanged ? nextState : state;
};
}
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(this, arguments));
};
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*/
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error("bindActionCreators expected an object or a function, instead received " + (actionCreators === null ? 'null' : typeof actionCreators) + ". " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?");
}
var keys = Object.keys(actionCreators);
var boundActionCreators = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/
function compose() {
for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
if (funcs.length === 0) {
return function (arg) {
return arg;
};
}
if (funcs.length === 1) {
return funcs[0];
}
return funcs.reduce(function (a, b) {
return function () {
return a(b.apply(void 0, arguments));
};
});
}
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
function applyMiddleware() {
for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function (createStore) {
return function () {
var store = createStore.apply(void 0, arguments);
var _dispatch = function dispatch() {
throw new Error("Dispatching while constructing your middleware is not allowed. " + "Other middleware would not be applied to this dispatch.");
};
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch() {
return _dispatch.apply(void 0, arguments);
}
};
var chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
_dispatch = compose.apply(void 0, chain)(store.dispatch);
return _objectSpread({}, store, {
dispatch: _dispatch
});
};
};
}
/*
* This is a dummy function to check if the function name has been altered by minification.
* If the function has been minified and NODE_ENV !== 'production', warn the user.
*/
function isCrushed() {}
if (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.');
}
exports.createStore = createStore;
exports.combineReducers = combineReducers;
exports.bindActionCreators = bindActionCreators;
exports.applyMiddleware = applyMiddleware;
exports.compose = compose;
exports.__DO_NOT_USE__ActionTypes = ActionTypes;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, module) {'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ponyfill = __webpack_require__(206);
var _ponyfill2 = _interopRequireDefault(_ponyfill);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var root; /* global window */
if (typeof self !== 'undefined') {
root = self;
} else if (typeof window !== 'undefined') {
root = window;
} else if (typeof global !== 'undefined') {
root = global;
} else if (true) {
root = module;
} else {
root = Function('return this')();
}
var result = (0, _ponyfill2['default'])(root);
exports['default'] = result;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(205)(module)))
/***/ }),
/* 205 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ }),
/* 206 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = symbolObservablePonyfill;
function symbolObservablePonyfill(root) {
var result;
var _Symbol = root.Symbol;
if (typeof _Symbol === 'function') {
if (_Symbol.observable) {
result = _Symbol.observable;
} else {
result = _Symbol('observable');
_Symbol.observable = result;
}
} else {
result = '@@observable';
}
return result;
};
/***/ }),
/* 207 */
/***/ (function(module, exports) {
'use strict';
var index = (function (fn) {
var lastArgs = [];
var frameId = null;
var wrapperFn = function wrapperFn() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
lastArgs = args;
if (frameId) {
return;
}
frameId = requestAnimationFrame(function () {
frameId = null;
fn.apply(undefined, lastArgs);
});
};
wrapperFn.cancel = function () {
if (!frameId) {
return;
}
cancelAnimationFrame(frameId);
frameId = null;
};
var resultFn = wrapperFn;
return resultFn;
});
module.exports = index;
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
var _Object$create = __webpack_require__(209);
function _inheritsLoose(subClass, superClass) {
subClass.prototype = _Object$create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
module.exports = _inheritsLoose;
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(210);
/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(211);
var $Object = __webpack_require__(163).Object;
module.exports = function create(P, D) {
return $Object.create(P, D);
};
/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(161);
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: __webpack_require__(212) });
/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(168);
var dPs = __webpack_require__(213);
var enumBugKeys = __webpack_require__(192);
var IE_PROTO = __webpack_require__(188)('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(173)('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
__webpack_require__(214).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(167);
var anObject = __webpack_require__(168);
var getKeys = __webpack_require__(178);
module.exports = __webpack_require__(171) ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = getKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
var document = __webpack_require__(162).document;
module.exports = document && document.documentElement;
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
var _interopRequireWildcard = __webpack_require__(216);
exports.__esModule = true;
var _Provider = _interopRequireWildcard(__webpack_require__(217));
exports.Provider = _Provider.default;
exports.createProvider = _Provider.createProvider;
var _connectAdvanced = _interopRequireDefault(__webpack_require__(221));
exports.connectAdvanced = _connectAdvanced.default;
var _connect = _interopRequireDefault(__webpack_require__(230));
exports.connect = _connect.default;
/***/ }),
/* 216 */
/***/ (function(module, exports) {
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
if (desc.get || desc.set) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
}
newObj.default = obj;
return newObj;
}
}
module.exports = _interopRequireWildcard;
/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.createProvider = createProvider;
exports.default = void 0;
var _inheritsLoose2 = _interopRequireDefault(__webpack_require__(218));
var _react = __webpack_require__(1);
var _propTypes = _interopRequireDefault(__webpack_require__(6));
var _PropTypes = __webpack_require__(219);
var _warning = _interopRequireDefault(__webpack_require__(220));
var didWarnAboutReceivingStore = false;
function warnAboutReceivingStore() {
if (didWarnAboutReceivingStore) {
return;
}
didWarnAboutReceivingStore = true;
(0, _warning.default)('<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/reduxjs/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.');
}
function createProvider(storeKey) {
var _Provider$childContex;
if (storeKey === void 0) {
storeKey = 'store';
}
var subscriptionKey = storeKey + "Subscription";
var Provider =
/*#__PURE__*/
function (_Component) {
(0, _inheritsLoose2.default)(Provider, _Component);
var _proto = Provider.prototype;
_proto.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[storeKey] = this[storeKey], _ref[subscriptionKey] = null, _ref;
};
function Provider(props, context) {
var _this;
_this = _Component.call(this, props, context) || this;
_this[storeKey] = props.store;
return _this;
}
_proto.render = function render() {
return _react.Children.only(this.props.children);
};
return Provider;
}(_react.Component);
if (process.env.NODE_ENV !== 'production') {
Provider.prototype.componentWillReceiveProps = function (nextProps) {
if (this[storeKey] !== nextProps.store) {
warnAboutReceivingStore();
}
};
}
Provider.propTypes = {
store: _PropTypes.storeShape.isRequired,
children: _propTypes.default.element.isRequired
};
Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[storeKey] = _PropTypes.storeShape.isRequired, _Provider$childContex[subscriptionKey] = _PropTypes.subscriptionShape, _Provider$childContex);
return Provider;
}
var _default = createProvider();
exports.default = _default;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 218 */
/***/ (function(module, exports) {
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
module.exports = _inheritsLoose;
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.storeShape = exports.subscriptionShape = void 0;
var _propTypes = _interopRequireDefault(__webpack_require__(6));
var subscriptionShape = _propTypes.default.shape({
trySubscribe: _propTypes.default.func.isRequired,
tryUnsubscribe: _propTypes.default.func.isRequired,
notifyNestedSubs: _propTypes.default.func.isRequired,
isSubscribed: _propTypes.default.func.isRequired
});
exports.subscriptionShape = subscriptionShape;
var storeShape = _propTypes.default.shape({
subscribe: _propTypes.default.func.isRequired,
dispatch: _propTypes.default.func.isRequired,
getState: _propTypes.default.func.isRequired
});
exports.storeShape = storeShape;
/***/ }),
/* 220 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = warning;
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that if you enable
// "break on all exceptions" in your console,
// it would pause the execution at this line.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = connectAdvanced;
var _inheritsLoose2 = _interopRequireDefault(__webpack_require__(218));
var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(222));
var _extends2 = _interopRequireDefault(__webpack_require__(122));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(__webpack_require__(223));
var _hoistNonReactStatics = _interopRequireDefault(__webpack_require__(224));
var _invariant = _interopRequireDefault(__webpack_require__(228));
var _react = __webpack_require__(1);
var _reactIs = __webpack_require__(225);
var _Subscription = _interopRequireDefault(__webpack_require__(229));
var _PropTypes = __webpack_require__(219);
var hotReloadingVersion = 0;
var dummyState = {};
function noop() {}
function makeSelectorStateful(sourceSelector, store) {
// wrap the selector in an object that tracks its results between runs.
var selector = {
run: function runComponentSelector(props) {
try {
var nextProps = sourceSelector(store.getState(), props);
if (nextProps !== selector.props || selector.error) {
selector.shouldComponentUpdate = true;
selector.props = nextProps;
selector.error = null;
}
} catch (error) {
selector.shouldComponentUpdate = true;
selector.error = error;
}
}
};
return selector;
}
function connectAdvanced(
/*
selectorFactory is a func that is responsible for returning the selector function used to
compute new props from state, props, and dispatch. For example:
export default connectAdvanced((dispatch, options) => (state, props) => ({
thing: state.things[props.thingId],
saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)),
}))(YourComponent)
Access to dispatch is provided to the factory so selectorFactories can bind actionCreators
outside of their selector as an optimization. Options passed to connectAdvanced are passed to
the selectorFactory, along with displayName and WrappedComponent, as the second argument.
Note that selectorFactory is responsible for all caching/memoization of inbound and outbound
props. Do not use connectAdvanced directly without memoizing results between calls to your
selector, otherwise the Connect component will re-render on every state or props change.
*/
selectorFactory, // options object:
_ref) {
var _contextTypes, _childContextTypes;
if (_ref === void 0) {
_ref = {};
}
var _ref2 = _ref,
_ref2$getDisplayName = _ref2.getDisplayName,
getDisplayName = _ref2$getDisplayName === void 0 ? function (name) {
return "ConnectAdvanced(" + name + ")";
} : _ref2$getDisplayName,
_ref2$methodName = _ref2.methodName,
methodName = _ref2$methodName === void 0 ? 'connectAdvanced' : _ref2$methodName,
_ref2$renderCountProp = _ref2.renderCountProp,
renderCountProp = _ref2$renderCountProp === void 0 ? undefined : _ref2$renderCountProp,
_ref2$shouldHandleSta = _ref2.shouldHandleStateChanges,
shouldHandleStateChanges = _ref2$shouldHandleSta === void 0 ? true : _ref2$shouldHandleSta,
_ref2$storeKey = _ref2.storeKey,
storeKey = _ref2$storeKey === void 0 ? 'store' : _ref2$storeKey,
_ref2$withRef = _ref2.withRef,
withRef = _ref2$withRef === void 0 ? false : _ref2$withRef,
connectOptions = (0, _objectWithoutPropertiesLoose2.default)(_ref2, ["getDisplayName", "methodName", "renderCountProp", "shouldHandleStateChanges", "storeKey", "withRef"]);
var subscriptionKey = storeKey + 'Subscription';
var version = hotReloadingVersion++;
var contextTypes = (_contextTypes = {}, _contextTypes[storeKey] = _PropTypes.storeShape, _contextTypes[subscriptionKey] = _PropTypes.subscriptionShape, _contextTypes);
var childContextTypes = (_childContextTypes = {}, _childContextTypes[subscriptionKey] = _PropTypes.subscriptionShape, _childContextTypes);
return function wrapWithConnect(WrappedComponent) {
(0, _invariant.default)((0, _reactIs.isValidElementType)(WrappedComponent), "You must pass a component to the function returned by " + (methodName + ". Instead received " + JSON.stringify(WrappedComponent)));
var wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
var displayName = getDisplayName(wrappedComponentName);
var selectorFactoryOptions = (0, _extends2.default)({}, connectOptions, {
getDisplayName: getDisplayName,
methodName: methodName,
renderCountProp: renderCountProp,
shouldHandleStateChanges: shouldHandleStateChanges,
storeKey: storeKey,
withRef: withRef,
displayName: displayName,
wrappedComponentName: wrappedComponentName,
WrappedComponent: WrappedComponent // TODO Actually fix our use of componentWillReceiveProps
/* eslint-disable react/no-deprecated */
});
var Connect =
/*#__PURE__*/
function (_Component) {
(0, _inheritsLoose2.default)(Connect, _Component);
function Connect(props, context) {
var _this;
_this = _Component.call(this, props, context) || this;
_this.version = version;
_this.state = {};
_this.renderCount = 0;
_this.store = props[storeKey] || context[storeKey];
_this.propsMode = Boolean(props[storeKey]);
_this.setWrappedInstance = _this.setWrappedInstance.bind((0, _assertThisInitialized2.default)((0, _assertThisInitialized2.default)(_this)));
(0, _invariant.default)(_this.store, "Could not find \"" + storeKey + "\" in either the context or props of " + ("\"" + displayName + "\". Either wrap the root component in a <Provider>, ") + ("or explicitly pass \"" + storeKey + "\" as a prop to \"" + displayName + "\"."));
_this.initSelector();
_this.initSubscription();
return _this;
}
var _proto = Connect.prototype;
_proto.getChildContext = function getChildContext() {
var _ref3;
// If this component received store from props, its subscription should be transparent
// to any descendants receiving store+subscription from context; it passes along
// subscription passed to it. Otherwise, it shadows the parent subscription, which allows
// Connect to control ordering of notifications to flow top-down.
var subscription = this.propsMode ? null : this.subscription;
return _ref3 = {}, _ref3[subscriptionKey] = subscription || this.context[subscriptionKey], _ref3;
};
_proto.componentDidMount = function componentDidMount() {
if (!shouldHandleStateChanges) return; // componentWillMount fires during server side rendering, but componentDidMount and
// componentWillUnmount do not. Because of this, trySubscribe happens during ...didMount.
// Otherwise, unsubscription would never take place during SSR, causing a memory leak.
// To handle the case where a child component may have triggered a state change by
// dispatching an action in its componentWillMount, we have to re-run the select and maybe
// re-render.
this.subscription.trySubscribe();
this.selector.run(this.props);
if (this.selector.shouldComponentUpdate) this.forceUpdate();
};
_proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
this.selector.run(nextProps);
};
_proto.shouldComponentUpdate = function shouldComponentUpdate() {
return this.selector.shouldComponentUpdate;
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.subscription) this.subscription.tryUnsubscribe();
this.subscription = null;
this.notifyNestedSubs = noop;
this.store = null;
this.selector.run = noop;
this.selector.shouldComponentUpdate = false;
};
_proto.getWrappedInstance = function getWrappedInstance() {
(0, _invariant.default)(withRef, "To access the wrapped instance, you need to specify " + ("{ withRef: true } in the options argument of the " + methodName + "() call."));
return this.wrappedInstance;
};
_proto.setWrappedInstance = function setWrappedInstance(ref) {
this.wrappedInstance = ref;
};
_proto.initSelector = function initSelector() {
var sourceSelector = selectorFactory(this.store.dispatch, selectorFactoryOptions);
this.selector = makeSelectorStateful(sourceSelector, this.store);
this.selector.run(this.props);
};
_proto.initSubscription = function initSubscription() {
if (!shouldHandleStateChanges) return; // parentSub's source should match where store came from: props vs. context. A component
// connected to the store via props shouldn't use subscription from context, or vice versa.
var parentSub = (this.propsMode ? this.props : this.context)[subscriptionKey];
this.subscription = new _Subscription.default(this.store, parentSub, this.onStateChange.bind(this)); // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in
// the middle of the notification loop, where `this.subscription` will then be null. An
// extra null check every change can be avoided by copying the method onto `this` and then
// replacing it with a no-op on unmount. This can probably be avoided if Subscription's
// listeners logic is changed to not call listeners that have been unsubscribed in the
// middle of the notification loop.
this.notifyNestedSubs = this.subscription.notifyNestedSubs.bind(this.subscription);
};
_proto.onStateChange = function onStateChange() {
this.selector.run(this.props);
if (!this.selector.shouldComponentUpdate) {
this.notifyNestedSubs();
} else {
this.componentDidUpdate = this.notifyNestedSubsOnComponentDidUpdate;
this.setState(dummyState);
}
};
_proto.notifyNestedSubsOnComponentDidUpdate = function notifyNestedSubsOnComponentDidUpdate() {
// `componentDidUpdate` is conditionally implemented when `onStateChange` determines it
// needs to notify nested subs. Once called, it unimplements itself until further state
// changes occur. Doing it this way vs having a permanent `componentDidUpdate` that does
// a boolean check every time avoids an extra method call most of the time, resulting
// in some perf boost.
this.componentDidUpdate = undefined;
this.notifyNestedSubs();
};
_proto.isSubscribed = function isSubscribed() {
return Boolean(this.subscription) && this.subscription.isSubscribed();
};
_proto.addExtraProps = function addExtraProps(props) {
if (!withRef && !renderCountProp && !(this.propsMode && this.subscription)) return props; // make a shallow copy so that fields added don't leak to the original selector.
// this is especially important for 'ref' since that's a reference back to the component
// instance. a singleton memoized selector would then be holding a reference to the
// instance, preventing the instance from being garbage collected, and that would be bad
var withExtras = (0, _extends2.default)({}, props);
if (withRef) withExtras.ref = this.setWrappedInstance;
if (renderCountProp) withExtras[renderCountProp] = this.renderCount++;
if (this.propsMode && this.subscription) withExtras[subscriptionKey] = this.subscription;
return withExtras;
};
_proto.render = function render() {
var selector = this.selector;
selector.shouldComponentUpdate = false;
if (selector.error) {
throw selector.error;
} else {
return (0, _react.createElement)(WrappedComponent, this.addExtraProps(selector.props));
}
};
return Connect;
}(_react.Component);
/* eslint-enable react/no-deprecated */
Connect.WrappedComponent = WrappedComponent;
Connect.displayName = displayName;
Connect.childContextTypes = childContextTypes;
Connect.contextTypes = contextTypes;
Connect.propTypes = contextTypes;
if (process.env.NODE_ENV !== 'production') {
Connect.prototype.componentWillUpdate = function componentWillUpdate() {
var _this2 = this;
// We are hot reloading!
if (this.version !== version) {
this.version = version;
this.initSelector(); // If any connected descendants don't hot reload (and resubscribe in the process), their
// listeners will be lost when we unsubscribe. Unfortunately, by copying over all
// listeners, this does mean that the old versions of connected descendants will still be
// notified of state changes; however, their onStateChange function is a no-op so this
// isn't a huge deal.
var oldListeners = [];
if (this.subscription) {
oldListeners = this.subscription.listeners.get();
this.subscription.tryUnsubscribe();
}
this.initSubscription();
if (shouldHandleStateChanges) {
this.subscription.trySubscribe();
oldListeners.forEach(function (listener) {
return _this2.subscription.listeners.subscribe(listener);
});
}
}
};
}
return (0, _hoistNonReactStatics.default)(Connect, WrappedComponent);
};
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 222 */
/***/ (function(module, exports) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized;
/***/ }),
/* 223 */
/***/ (function(module, exports) {
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
module.exports = _objectWithoutPropertiesLoose;
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var ReactIs = __webpack_require__(225);
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[ReactIs.ForwardRef] = FORWARD_REF_STATICS;
function getStatics(component) {
if (ReactIs.isMemo(component)) {
return MEMO_STATICS;
}
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
return targetComponent;
}
return targetComponent;
}
module.exports = hoistNonReactStatics;
/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = __webpack_require__(226);
} else {
module.exports = __webpack_require__(227);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 226 */
/***/ (function(module, exports) {
/** @license React v16.8.4
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';Object.defineProperty(exports,"__esModule",{value:!0});
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?Symbol.for("react.memo"):
60115,r=b?Symbol.for("react.lazy"):60116;function t(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case h:return a;default:return u}}case r:case q:case d:return u}}}function v(a){return t(a)===m}exports.typeOf=t;exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;
exports.Fragment=e;exports.Lazy=r;exports.Memo=q;exports.Portal=d;exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||"object"===typeof a&&null!==a&&(a.$$typeof===r||a.$$typeof===q||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n)};exports.isAsyncMode=function(a){return v(a)||t(a)===l};exports.isConcurrentMode=v;exports.isContextConsumer=function(a){return t(a)===k};
exports.isContextProvider=function(a){return t(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return t(a)===n};exports.isFragment=function(a){return t(a)===e};exports.isLazy=function(a){return t(a)===r};exports.isMemo=function(a){return t(a)===q};exports.isPortal=function(a){return t(a)===d};exports.isProfiler=function(a){return t(a)===g};exports.isStrictMode=function(a){return t(a)===f};
exports.isSuspense=function(a){return t(a)===p};
/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/** @license React v16.8.4
* react-is.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
if (process.env.NODE_ENV !== "production") {
(function() {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' ||
// Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
}
/**
* 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 () {};
{
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('`lowPriorityWarning(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));
}
};
}
var lowPriorityWarning$1 = lowPriorityWarning;
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
}
// AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
// AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.typeOf = typeOf;
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isValidElementType = isValidElementType;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
})();
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 229 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = void 0;
// encapsulates the subscription logic for connecting a component to the redux store, as
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants
var CLEARED = null;
var nullListeners = {
notify: function notify() {}
};
function createListenerCollection() {
// the current/next pattern is copied from redux's createStore code.
// TODO: refactor+expose that code to be reusable here?
var current = [];
var next = [];
return {
clear: function clear() {
next = CLEARED;
current = CLEARED;
},
notify: function notify() {
var listeners = current = next;
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
},
get: function get() {
return next;
},
subscribe: function subscribe(listener) {
var isSubscribed = true;
if (next === current) next = current.slice();
next.push(listener);
return function unsubscribe() {
if (!isSubscribed || current === CLEARED) return;
isSubscribed = false;
if (next === current) next = current.slice();
next.splice(next.indexOf(listener), 1);
};
}
};
}
var Subscription =
/*#__PURE__*/
function () {
function Subscription(store, parentSub, onStateChange) {
this.store = store;
this.parentSub = parentSub;
this.onStateChange = onStateChange;
this.unsubscribe = null;
this.listeners = nullListeners;
}
var _proto = Subscription.prototype;
_proto.addNestedSub = function addNestedSub(listener) {
this.trySubscribe();
return this.listeners.subscribe(listener);
};
_proto.notifyNestedSubs = function notifyNestedSubs() {
this.listeners.notify();
};
_proto.isSubscribed = function isSubscribed() {
return Boolean(this.unsubscribe);
};
_proto.trySubscribe = function trySubscribe() {
if (!this.unsubscribe) {
this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.onStateChange) : this.store.subscribe(this.onStateChange);
this.listeners = createListenerCollection();
}
};
_proto.tryUnsubscribe = function tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
this.listeners.clear();
this.listeners = nullListeners;
}
};
return Subscription;
}();
exports.default = Subscription;
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.createConnect = createConnect;
exports.default = void 0;
var _extends2 = _interopRequireDefault(__webpack_require__(122));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(__webpack_require__(223));
var _connectAdvanced = _interopRequireDefault(__webpack_require__(221));
var _shallowEqual = _interopRequireDefault(__webpack_require__(231));
var _mapDispatchToProps = _interopRequireDefault(__webpack_require__(232));
var _mapStateToProps = _interopRequireDefault(__webpack_require__(236));
var _mergeProps = _interopRequireDefault(__webpack_require__(237));
var _selectorFactory = _interopRequireDefault(__webpack_require__(238));
/*
connect is a facade over connectAdvanced. It turns its args into a compatible
selectorFactory, which has the signature:
(dispatch, options) => (nextState, nextOwnProps) => nextFinalProps
connect passes its args to connectAdvanced as options, which will in turn pass them to
selectorFactory each time a Connect component instance is instantiated or hot reloaded.
selectorFactory returns a final props selector from its mapStateToProps,
mapStateToPropsFactories, mapDispatchToProps, mapDispatchToPropsFactories, mergeProps,
mergePropsFactories, and pure args.
The resulting final props selector is called by the Connect component instance whenever
it receives new props or store state.
*/
function match(arg, factories, name) {
for (var i = factories.length - 1; i >= 0; i--) {
var result = factories[i](arg);
if (result) return result;
}
return function (dispatch, options) {
throw new Error("Invalid value of type " + typeof arg + " for " + name + " argument when connecting component " + options.wrappedComponentName + ".");
};
}
function strictEqual(a, b) {
return a === b;
} // createConnect with default args builds the 'official' connect behavior. Calling it with
// different options opens up some testing and extensibility scenarios
function createConnect(_temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$connectHOC = _ref.connectHOC,
connectHOC = _ref$connectHOC === void 0 ? _connectAdvanced.default : _ref$connectHOC,
_ref$mapStateToPropsF = _ref.mapStateToPropsFactories,
mapStateToPropsFactories = _ref$mapStateToPropsF === void 0 ? _mapStateToProps.default : _ref$mapStateToPropsF,
_ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories,
mapDispatchToPropsFactories = _ref$mapDispatchToPro === void 0 ? _mapDispatchToProps.default : _ref$mapDispatchToPro,
_ref$mergePropsFactor = _ref.mergePropsFactories,
mergePropsFactories = _ref$mergePropsFactor === void 0 ? _mergeProps.default : _ref$mergePropsFactor,
_ref$selectorFactory = _ref.selectorFactory,
selectorFactory = _ref$selectorFactory === void 0 ? _selectorFactory.default : _ref$selectorFactory;
return function connect(mapStateToProps, mapDispatchToProps, mergeProps, _ref2) {
if (_ref2 === void 0) {
_ref2 = {};
}
var _ref3 = _ref2,
_ref3$pure = _ref3.pure,
pure = _ref3$pure === void 0 ? true : _ref3$pure,
_ref3$areStatesEqual = _ref3.areStatesEqual,
areStatesEqual = _ref3$areStatesEqual === void 0 ? strictEqual : _ref3$areStatesEqual,
_ref3$areOwnPropsEqua = _ref3.areOwnPropsEqual,
areOwnPropsEqual = _ref3$areOwnPropsEqua === void 0 ? _shallowEqual.default : _ref3$areOwnPropsEqua,
_ref3$areStatePropsEq = _ref3.areStatePropsEqual,
areStatePropsEqual = _ref3$areStatePropsEq === void 0 ? _shallowEqual.default : _ref3$areStatePropsEq,
_ref3$areMergedPropsE = _ref3.areMergedPropsEqual,
areMergedPropsEqual = _ref3$areMergedPropsE === void 0 ? _shallowEqual.default : _ref3$areMergedPropsE,
extraOptions = (0, _objectWithoutPropertiesLoose2.default)(_ref3, ["pure", "areStatesEqual", "areOwnPropsEqual", "areStatePropsEqual", "areMergedPropsEqual"]);
var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps');
var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps');
var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps');
return connectHOC(selectorFactory, (0, _extends2.default)({
// used in error messages
methodName: 'connect',
// used to compute Connect's displayName from the wrapped component's displayName.
getDisplayName: function getDisplayName(name) {
return "Connect(" + name + ")";
},
// if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes
shouldHandleStateChanges: Boolean(mapStateToProps),
// passed through to selectorFactory
initMapStateToProps: initMapStateToProps,
initMapDispatchToProps: initMapDispatchToProps,
initMergeProps: initMergeProps,
pure: pure,
areStatesEqual: areStatesEqual,
areOwnPropsEqual: areOwnPropsEqual,
areStatePropsEqual: areStatePropsEqual,
areMergedPropsEqual: areMergedPropsEqual
}, extraOptions));
};
}
var _default = createConnect();
exports.default = _default;
/***/ }),
/* 231 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = shallowEqual;
var hasOwn = Object.prototype.hasOwnProperty;
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function shallowEqual(objA, objB) {
if (is(objA, objB)) return true;
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.whenMapDispatchToPropsIsFunction = whenMapDispatchToPropsIsFunction;
exports.whenMapDispatchToPropsIsMissing = whenMapDispatchToPropsIsMissing;
exports.whenMapDispatchToPropsIsObject = whenMapDispatchToPropsIsObject;
exports.default = void 0;
var _redux = __webpack_require__(203);
var _wrapMapToProps = __webpack_require__(233);
function whenMapDispatchToPropsIsFunction(mapDispatchToProps) {
return typeof mapDispatchToProps === 'function' ? (0, _wrapMapToProps.wrapMapToPropsFunc)(mapDispatchToProps, 'mapDispatchToProps') : undefined;
}
function whenMapDispatchToPropsIsMissing(mapDispatchToProps) {
return !mapDispatchToProps ? (0, _wrapMapToProps.wrapMapToPropsConstant)(function (dispatch) {
return {
dispatch: dispatch
};
}) : undefined;
}
function whenMapDispatchToPropsIsObject(mapDispatchToProps) {
return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? (0, _wrapMapToProps.wrapMapToPropsConstant)(function (dispatch) {
return (0, _redux.bindActionCreators)(mapDispatchToProps, dispatch);
}) : undefined;
}
var _default = [whenMapDispatchToPropsIsFunction, whenMapDispatchToPropsIsMissing, whenMapDispatchToPropsIsObject];
exports.default = _default;
/***/ }),
/* 233 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.wrapMapToPropsConstant = wrapMapToPropsConstant;
exports.getDependsOnOwnProps = getDependsOnOwnProps;
exports.wrapMapToPropsFunc = wrapMapToPropsFunc;
var _verifyPlainObject = _interopRequireDefault(__webpack_require__(234));
function wrapMapToPropsConstant(getConstant) {
return function initConstantSelector(dispatch, options) {
var constant = getConstant(dispatch, options);
function constantSelector() {
return constant;
}
constantSelector.dependsOnOwnProps = false;
return constantSelector;
};
} // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args
// to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine
// whether mapToProps needs to be invoked when props have changed.
//
// A length of one signals that mapToProps does not depend on props from the parent component.
// A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and
// therefore not reporting its length accurately..
function getDependsOnOwnProps(mapToProps) {
return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;
} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,
// this function wraps mapToProps in a proxy function which does several things:
//
// * Detects whether the mapToProps function being called depends on props, which
// is used by selectorFactory to decide if it should reinvoke on props changes.
//
// * On first call, handles mapToProps if returns another function, and treats that
// new function as the true mapToProps for subsequent calls.
//
// * On first call, verifies the first result is a plain object, in order to warn
// the developer that their mapToProps function is not returning a valid result.
//
function wrapMapToPropsFunc(mapToProps, methodName) {
return function initProxySelector(dispatch, _ref) {
var displayName = _ref.displayName;
var proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {
return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch);
}; // allow detectFactoryAndVerify to get ownProps
proxy.dependsOnOwnProps = true;
proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {
proxy.mapToProps = mapToProps;
proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);
var props = proxy(stateOrDispatch, ownProps);
if (typeof props === 'function') {
proxy.mapToProps = props;
proxy.dependsOnOwnProps = getDependsOnOwnProps(props);
props = proxy(stateOrDispatch, ownProps);
}
if (process.env.NODE_ENV !== 'production') (0, _verifyPlainObject.default)(props, displayName, methodName);
return props;
};
return proxy;
};
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = verifyPlainObject;
var _isPlainObject = _interopRequireDefault(__webpack_require__(235));
var _warning = _interopRequireDefault(__webpack_require__(220));
function verifyPlainObject(value, displayName, methodName) {
if (!(0, _isPlainObject.default)(value)) {
(0, _warning.default)(methodName + "() in " + displayName + " must return a plain object. Instead received " + value + ".");
}
}
/***/ }),
/* 235 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = isPlainObject;
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false;
var proto = Object.getPrototypeOf(obj);
if (proto === null) return true;
var baseProto = proto;
while (Object.getPrototypeOf(baseProto) !== null) {
baseProto = Object.getPrototypeOf(baseProto);
}
return proto === baseProto;
}
/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.whenMapStateToPropsIsFunction = whenMapStateToPropsIsFunction;
exports.whenMapStateToPropsIsMissing = whenMapStateToPropsIsMissing;
exports.default = void 0;
var _wrapMapToProps = __webpack_require__(233);
function whenMapStateToPropsIsFunction(mapStateToProps) {
return typeof mapStateToProps === 'function' ? (0, _wrapMapToProps.wrapMapToPropsFunc)(mapStateToProps, 'mapStateToProps') : undefined;
}
function whenMapStateToPropsIsMissing(mapStateToProps) {
return !mapStateToProps ? (0, _wrapMapToProps.wrapMapToPropsConstant)(function () {
return {};
}) : undefined;
}
var _default = [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing];
exports.default = _default;
/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.defaultMergeProps = defaultMergeProps;
exports.wrapMergePropsFunc = wrapMergePropsFunc;
exports.whenMergePropsIsFunction = whenMergePropsIsFunction;
exports.whenMergePropsIsOmitted = whenMergePropsIsOmitted;
exports.default = void 0;
var _extends2 = _interopRequireDefault(__webpack_require__(122));
var _verifyPlainObject = _interopRequireDefault(__webpack_require__(234));
function defaultMergeProps(stateProps, dispatchProps, ownProps) {
return (0, _extends2.default)({}, ownProps, stateProps, dispatchProps);
}
function wrapMergePropsFunc(mergeProps) {
return function initMergePropsProxy(dispatch, _ref) {
var displayName = _ref.displayName,
pure = _ref.pure,
areMergedPropsEqual = _ref.areMergedPropsEqual;
var hasRunOnce = false;
var mergedProps;
return function mergePropsProxy(stateProps, dispatchProps, ownProps) {
var nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);
if (hasRunOnce) {
if (!pure || !areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps;
} else {
hasRunOnce = true;
mergedProps = nextMergedProps;
if (process.env.NODE_ENV !== 'production') (0, _verifyPlainObject.default)(mergedProps, displayName, 'mergeProps');
}
return mergedProps;
};
};
}
function whenMergePropsIsFunction(mergeProps) {
return typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : undefined;
}
function whenMergePropsIsOmitted(mergeProps) {
return !mergeProps ? function () {
return defaultMergeProps;
} : undefined;
}
var _default = [whenMergePropsIsFunction, whenMergePropsIsOmitted];
exports.default = _default;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.impureFinalPropsSelectorFactory = impureFinalPropsSelectorFactory;
exports.pureFinalPropsSelectorFactory = pureFinalPropsSelectorFactory;
exports.default = finalPropsSelectorFactory;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(__webpack_require__(223));
var _verifySubselectors = _interopRequireDefault(__webpack_require__(239));
function impureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch) {
return function impureFinalPropsSelector(state, ownProps) {
return mergeProps(mapStateToProps(state, ownProps), mapDispatchToProps(dispatch, ownProps), ownProps);
};
}
function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, _ref) {
var areStatesEqual = _ref.areStatesEqual,
areOwnPropsEqual = _ref.areOwnPropsEqual,
areStatePropsEqual = _ref.areStatePropsEqual;
var hasRunAtLeastOnce = false;
var state;
var ownProps;
var stateProps;
var dispatchProps;
var mergedProps;
function handleFirstCall(firstState, firstOwnProps) {
state = firstState;
ownProps = firstOwnProps;
stateProps = mapStateToProps(state, ownProps);
dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
hasRunAtLeastOnce = true;
return mergedProps;
}
function handleNewPropsAndNewState() {
stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewProps() {
if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewState() {
var nextStateProps = mapStateToProps(state, ownProps);
var statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps);
stateProps = nextStateProps;
if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleSubsequentCalls(nextState, nextOwnProps) {
var propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);
var stateChanged = !areStatesEqual(nextState, state);
state = nextState;
ownProps = nextOwnProps;
if (propsChanged && stateChanged) return handleNewPropsAndNewState();
if (propsChanged) return handleNewProps();
if (stateChanged) return handleNewState();
return mergedProps;
}
return function pureFinalPropsSelector(nextState, nextOwnProps) {
return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps);
};
} // TODO: Add more comments
// If pure is true, the selector returned by selectorFactory will memoize its results,
// allowing connectAdvanced's shouldComponentUpdate to return false if final
// props have not changed. If false, the selector will always return a new
// object and shouldComponentUpdate will always return true.
function finalPropsSelectorFactory(dispatch, _ref2) {
var initMapStateToProps = _ref2.initMapStateToProps,
initMapDispatchToProps = _ref2.initMapDispatchToProps,
initMergeProps = _ref2.initMergeProps,
options = (0, _objectWithoutPropertiesLoose2.default)(_ref2, ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"]);
var mapStateToProps = initMapStateToProps(dispatch, options);
var mapDispatchToProps = initMapDispatchToProps(dispatch, options);
var mergeProps = initMergeProps(dispatch, options);
if (process.env.NODE_ENV !== 'production') {
(0, _verifySubselectors.default)(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName);
}
var selectorFactory = options.pure ? pureFinalPropsSelectorFactory : impureFinalPropsSelectorFactory;
return selectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(14);
exports.__esModule = true;
exports.default = verifySubselectors;
var _warning = _interopRequireDefault(__webpack_require__(220));
function verify(selector, methodName, displayName) {
if (!selector) {
throw new Error("Unexpected value for " + methodName + " in " + displayName + ".");
} else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') {
if (!selector.hasOwnProperty('dependsOnOwnProps')) {
(0, _warning.default)("The selector for " + methodName + " of " + displayName + " did not specify a value for dependsOnOwnProps.");
}
}
}
function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, displayName) {
verify(mapStateToProps, 'mapStateToProps', displayName);
verify(mapDispatchToProps, 'mapDispatchToProps', displayName);
verify(mergeProps, 'mergeProps', displayName);
}
/***/ }),
/* 240 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; }
var _Motion = __webpack_require__(241);
exports.Motion = _interopRequire(_Motion);
var _StaggeredMotion = __webpack_require__(248);
exports.StaggeredMotion = _interopRequire(_StaggeredMotion);
var _TransitionMotion = __webpack_require__(249);
exports.TransitionMotion = _interopRequire(_TransitionMotion);
var _spring = __webpack_require__(251);
exports.spring = _interopRequire(_spring);
var _presets = __webpack_require__(252);
exports.presets = _interopRequire(_presets);
var _stripStyle = __webpack_require__(243);
exports.stripStyle = _interopRequire(_stripStyle);
// deprecated, dummy warning function
var _reorderKeys = __webpack_require__(253);
exports.reorderKeys = _interopRequire(_reorderKeys);
/***/ }),
/* 241 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _mapToZero = __webpack_require__(242);
var _mapToZero2 = _interopRequireDefault(_mapToZero);
var _stripStyle = __webpack_require__(243);
var _stripStyle2 = _interopRequireDefault(_stripStyle);
var _stepper3 = __webpack_require__(244);
var _stepper4 = _interopRequireDefault(_stepper3);
var _performanceNow = __webpack_require__(245);
var _performanceNow2 = _interopRequireDefault(_performanceNow);
var _raf = __webpack_require__(246);
var _raf2 = _interopRequireDefault(_raf);
var _shouldStopAnimation = __webpack_require__(247);
var _shouldStopAnimation2 = _interopRequireDefault(_shouldStopAnimation);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var msPerFrame = 1000 / 60;
var Motion = (function (_React$Component) {
_inherits(Motion, _React$Component);
_createClass(Motion, null, [{
key: 'propTypes',
value: {
// TOOD: warn against putting a config in here
defaultStyle: _propTypes2['default'].objectOf(_propTypes2['default'].number),
style: _propTypes2['default'].objectOf(_propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].object])).isRequired,
children: _propTypes2['default'].func.isRequired,
onRest: _propTypes2['default'].func
},
enumerable: true
}]);
function Motion(props) {
var _this = this;
_classCallCheck(this, Motion);
_React$Component.call(this, props);
this.wasAnimating = false;
this.animationID = null;
this.prevTime = 0;
this.accumulatedTime = 0;
this.unreadPropStyle = null;
this.clearUnreadPropStyle = function (destStyle) {
var dirty = false;
var _state = _this.state;
var currentStyle = _state.currentStyle;
var currentVelocity = _state.currentVelocity;
var lastIdealStyle = _state.lastIdealStyle;
var lastIdealVelocity = _state.lastIdealVelocity;
for (var key in destStyle) {
if (!Object.prototype.hasOwnProperty.call(destStyle, key)) {
continue;
}
var styleValue = destStyle[key];
if (typeof styleValue === 'number') {
if (!dirty) {
dirty = true;
currentStyle = _extends({}, currentStyle);
currentVelocity = _extends({}, currentVelocity);
lastIdealStyle = _extends({}, lastIdealStyle);
lastIdealVelocity = _extends({}, lastIdealVelocity);
}
currentStyle[key] = styleValue;
currentVelocity[key] = 0;
lastIdealStyle[key] = styleValue;
lastIdealVelocity[key] = 0;
}
}
if (dirty) {
_this.setState({ currentStyle: currentStyle, currentVelocity: currentVelocity, lastIdealStyle: lastIdealStyle, lastIdealVelocity: lastIdealVelocity });
}
};
this.startAnimationIfNecessary = function () {
// TODO: when config is {a: 10} and dest is {a: 10} do we raf once and
// call cb? No, otherwise accidental parent rerender causes cb trigger
_this.animationID = _raf2['default'](function (timestamp) {
// check if we need to animate in the first place
var propsStyle = _this.props.style;
if (_shouldStopAnimation2['default'](_this.state.currentStyle, propsStyle, _this.state.currentVelocity)) {
if (_this.wasAnimating && _this.props.onRest) {
_this.props.onRest();
}
// no need to cancel animationID here; shouldn't have any in flight
_this.animationID = null;
_this.wasAnimating = false;
_this.accumulatedTime = 0;
return;
}
_this.wasAnimating = true;
var currentTime = timestamp || _performanceNow2['default']();
var timeDelta = currentTime - _this.prevTime;
_this.prevTime = currentTime;
_this.accumulatedTime = _this.accumulatedTime + timeDelta;
// more than 10 frames? prolly switched browser tab. Restart
if (_this.accumulatedTime > msPerFrame * 10) {
_this.accumulatedTime = 0;
}
if (_this.accumulatedTime === 0) {
// no need to cancel animationID here; shouldn't have any in flight
_this.animationID = null;
_this.startAnimationIfNecessary();
return;
}
var currentFrameCompletion = (_this.accumulatedTime - Math.floor(_this.accumulatedTime / msPerFrame) * msPerFrame) / msPerFrame;
var framesToCatchUp = Math.floor(_this.accumulatedTime / msPerFrame);
var newLastIdealStyle = {};
var newLastIdealVelocity = {};
var newCurrentStyle = {};
var newCurrentVelocity = {};
for (var key in propsStyle) {
if (!Object.prototype.hasOwnProperty.call(propsStyle, key)) {
continue;
}
var styleValue = propsStyle[key];
if (typeof styleValue === 'number') {
newCurrentStyle[key] = styleValue;
newCurrentVelocity[key] = 0;
newLastIdealStyle[key] = styleValue;
newLastIdealVelocity[key] = 0;
} else {
var newLastIdealStyleValue = _this.state.lastIdealStyle[key];
var newLastIdealVelocityValue = _this.state.lastIdealVelocity[key];
for (var i = 0; i < framesToCatchUp; i++) {
var _stepper = _stepper4['default'](msPerFrame / 1000, newLastIdealStyleValue, newLastIdealVelocityValue, styleValue.val, styleValue.stiffness, styleValue.damping, styleValue.precision);
newLastIdealStyleValue = _stepper[0];
newLastIdealVelocityValue = _stepper[1];
}
var _stepper2 = _stepper4['default'](msPerFrame / 1000, newLastIdealStyleValue, newLastIdealVelocityValue, styleValue.val, styleValue.stiffness, styleValue.damping, styleValue.precision);
var nextIdealX = _stepper2[0];
var nextIdealV = _stepper2[1];
newCurrentStyle[key] = newLastIdealStyleValue + (nextIdealX - newLastIdealStyleValue) * currentFrameCompletion;
newCurrentVelocity[key] = newLastIdealVelocityValue + (nextIdealV - newLastIdealVelocityValue) * currentFrameCompletion;
newLastIdealStyle[key] = newLastIdealStyleValue;
newLastIdealVelocity[key] = newLastIdealVelocityValue;
}
}
_this.animationID = null;
// the amount we're looped over above
_this.accumulatedTime -= framesToCatchUp * msPerFrame;
_this.setState({
currentStyle: newCurrentStyle,
currentVelocity: newCurrentVelocity,
lastIdealStyle: newLastIdealStyle,
lastIdealVelocity: newLastIdealVelocity
});
_this.unreadPropStyle = null;
_this.startAnimationIfNecessary();
});
};
this.state = this.defaultState();
}
Motion.prototype.defaultState = function defaultState() {
var _props = this.props;
var defaultStyle = _props.defaultStyle;
var style = _props.style;
var currentStyle = defaultStyle || _stripStyle2['default'](style);
var currentVelocity = _mapToZero2['default'](currentStyle);
return {
currentStyle: currentStyle,
currentVelocity: currentVelocity,
lastIdealStyle: currentStyle,
lastIdealVelocity: currentVelocity
};
};
// it's possible that currentStyle's value is stale: if props is immediately
// changed from 0 to 400 to spring(0) again, the async currentStyle is still
// at 0 (didn't have time to tick and interpolate even once). If we naively
// compare currentStyle with destVal it'll be 0 === 0 (no animation, stop).
// In reality currentStyle should be 400
Motion.prototype.componentDidMount = function componentDidMount() {
this.prevTime = _performanceNow2['default']();
this.startAnimationIfNecessary();
};
Motion.prototype.componentWillReceiveProps = function componentWillReceiveProps(props) {
if (this.unreadPropStyle != null) {
// previous props haven't had the chance to be set yet; set them here
this.clearUnreadPropStyle(this.unreadPropStyle);
}
this.unreadPropStyle = props.style;
if (this.animationID == null) {
this.prevTime = _performanceNow2['default']();
this.startAnimationIfNecessary();
}
};
Motion.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.animationID != null) {
_raf2['default'].cancel(this.animationID);
this.animationID = null;
}
};
Motion.prototype.render = function render() {
var renderedChildren = this.props.children(this.state.currentStyle);
return renderedChildren && _react2['default'].Children.only(renderedChildren);
};
return Motion;
})(_react2['default'].Component);
exports['default'] = Motion;
module.exports = exports['default'];
// after checking for unreadPropStyle != null, we manually go set the
// non-interpolating values (those that are a number, without a spring
// config)
/***/ }),
/* 242 */
/***/ (function(module, exports) {
// currently used to initiate the velocity style object to 0
'use strict';
exports.__esModule = true;
exports['default'] = mapToZero;
function mapToZero(obj) {
var ret = {};
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
ret[key] = 0;
}
}
return ret;
}
module.exports = exports['default'];
/***/ }),
/* 243 */
/***/ (function(module, exports) {
// turn {x: {val: 1, stiffness: 1, damping: 2}, y: 2} generated by
// `{x: spring(1, {stiffness: 1, damping: 2}), y: 2}` into {x: 1, y: 2}
'use strict';
exports.__esModule = true;
exports['default'] = stripStyle;
function stripStyle(style) {
var ret = {};
for (var key in style) {
if (!Object.prototype.hasOwnProperty.call(style, key)) {
continue;
}
ret[key] = typeof style[key] === 'number' ? style[key] : style[key].val;
}
return ret;
}
module.exports = exports['default'];
/***/ }),
/* 244 */
/***/ (function(module, exports) {
// stepper is used a lot. Saves allocation to return the same array wrapper.
// This is fine and danger-free against mutations because the callsite
// immediately destructures it and gets the numbers inside without passing the
"use strict";
exports.__esModule = true;
exports["default"] = stepper;
var reusedTuple = [0, 0];
function stepper(secondPerFrame, x, v, destX, k, b, precision) {
// Spring stiffness, in kg / s^2
// for animations, destX is really spring length (spring at rest). initial
// position is considered as the stretched/compressed position of a spring
var Fspring = -k * (x - destX);
// Damping, in kg / s
var Fdamper = -b * v;
// usually we put mass here, but for animation purposes, specifying mass is a
// bit redundant. you could simply adjust k and b accordingly
// let a = (Fspring + Fdamper) / mass;
var a = Fspring + Fdamper;
var newV = v + a * secondPerFrame;
var newX = x + newV * secondPerFrame;
if (Math.abs(newV) < precision && Math.abs(newX - destX) < precision) {
reusedTuple[0] = destX;
reusedTuple[1] = 0;
return reusedTuple;
}
reusedTuple[0] = newX;
reusedTuple[1] = newV;
return reusedTuple;
}
module.exports = exports["default"];
// array reference around.
/***/ }),
/* 245 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {// Generated by CoffeeScript 1.12.2
(function() {
var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
module.exports = function() {
return performance.now();
};
} else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
module.exports = function() {
return (getNanoSeconds() - nodeLoadTime) / 1e6;
};
hrtime = process.hrtime;
getNanoSeconds = function() {
var hr;
hr = hrtime();
return hr[0] * 1e9 + hr[1];
};
moduleLoadTime = getNanoSeconds();
upTime = process.uptime() * 1e9;
nodeLoadTime = moduleLoadTime - upTime;
} else if (Date.now) {
module.exports = function() {
return Date.now() - loadTime;
};
loadTime = Date.now();
} else {
module.exports = function() {
return new Date().getTime() - loadTime;
};
loadTime = new Date().getTime();
}
}).call(this);
//# sourceMappingURL=performance-now.js.map
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 246 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var now = __webpack_require__(245)
, root = typeof window === 'undefined' ? global : window
, vendors = ['moz', 'webkit']
, suffix = 'AnimationFrame'
, raf = root['request' + suffix]
, caf = root['cancel' + suffix] || root['cancelRequest' + suffix]
for(var i = 0; !raf && i < vendors.length; i++) {
raf = root[vendors[i] + 'Request' + suffix]
caf = root[vendors[i] + 'Cancel' + suffix]
|| root[vendors[i] + 'CancelRequest' + suffix]
}
// Some versions of FF have rAF but not cAF
if(!raf || !caf) {
var last = 0
, id = 0
, queue = []
, frameDuration = 1000 / 60
raf = function(callback) {
if(queue.length === 0) {
var _now = now()
, next = Math.max(0, frameDuration - (_now - last))
last = next + _now
setTimeout(function() {
var cp = queue.slice(0)
// Clear queue here to prevent
// callbacks from appending listeners
// to the current frame's queue
queue.length = 0
for(var i = 0; i < cp.length; i++) {
if(!cp[i].cancelled) {
try{
cp[i].callback(last)
} catch(e) {
setTimeout(function() { throw e }, 0)
}
}
}
}, Math.round(next))
}
queue.push({
handle: ++id,
callback: callback,
cancelled: false
})
return id
}
caf = function(handle) {
for(var i = 0; i < queue.length; i++) {
if(queue[i].handle === handle) {
queue[i].cancelled = true
}
}
}
}
module.exports = function(fn) {
// Wrap in a new function to prevent
// `cancel` potentially being assigned
// to the native rAF function
return raf.call(root, fn)
}
module.exports.cancel = function() {
caf.apply(root, arguments)
}
module.exports.polyfill = function(object) {
if (!object) {
object = root;
}
object.requestAnimationFrame = raf
object.cancelAnimationFrame = caf
}
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }),
/* 247 */
/***/ (function(module, exports) {
// usage assumption: currentStyle values have already been rendered but it says
// nothing of whether currentStyle is stale (see unreadPropStyle)
'use strict';
exports.__esModule = true;
exports['default'] = shouldStopAnimation;
function shouldStopAnimation(currentStyle, style, currentVelocity) {
for (var key in style) {
if (!Object.prototype.hasOwnProperty.call(style, key)) {
continue;
}
if (currentVelocity[key] !== 0) {
return false;
}
var styleValue = typeof style[key] === 'number' ? style[key] : style[key].val;
// stepper will have already taken care of rounding precision errors, so
// won't have such thing as 0.9999 !=== 1
if (currentStyle[key] !== styleValue) {
return false;
}
}
return true;
}
module.exports = exports['default'];
/***/ }),
/* 248 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _mapToZero = __webpack_require__(242);
var _mapToZero2 = _interopRequireDefault(_mapToZero);
var _stripStyle = __webpack_require__(243);
var _stripStyle2 = _interopRequireDefault(_stripStyle);
var _stepper3 = __webpack_require__(244);
var _stepper4 = _interopRequireDefault(_stepper3);
var _performanceNow = __webpack_require__(245);
var _performanceNow2 = _interopRequireDefault(_performanceNow);
var _raf = __webpack_require__(246);
var _raf2 = _interopRequireDefault(_raf);
var _shouldStopAnimation = __webpack_require__(247);
var _shouldStopAnimation2 = _interopRequireDefault(_shouldStopAnimation);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var msPerFrame = 1000 / 60;
function shouldStopAnimationAll(currentStyles, styles, currentVelocities) {
for (var i = 0; i < currentStyles.length; i++) {
if (!_shouldStopAnimation2['default'](currentStyles[i], styles[i], currentVelocities[i])) {
return false;
}
}
return true;
}
var StaggeredMotion = (function (_React$Component) {
_inherits(StaggeredMotion, _React$Component);
_createClass(StaggeredMotion, null, [{
key: 'propTypes',
value: {
// TOOD: warn against putting a config in here
defaultStyles: _propTypes2['default'].arrayOf(_propTypes2['default'].objectOf(_propTypes2['default'].number)),
styles: _propTypes2['default'].func.isRequired,
children: _propTypes2['default'].func.isRequired
},
enumerable: true
}]);
function StaggeredMotion(props) {
var _this = this;
_classCallCheck(this, StaggeredMotion);
_React$Component.call(this, props);
this.animationID = null;
this.prevTime = 0;
this.accumulatedTime = 0;
this.unreadPropStyles = null;
this.clearUnreadPropStyle = function (unreadPropStyles) {
var _state = _this.state;
var currentStyles = _state.currentStyles;
var currentVelocities = _state.currentVelocities;
var lastIdealStyles = _state.lastIdealStyles;
var lastIdealVelocities = _state.lastIdealVelocities;
var someDirty = false;
for (var i = 0; i < unreadPropStyles.length; i++) {
var unreadPropStyle = unreadPropStyles[i];
var dirty = false;
for (var key in unreadPropStyle) {
if (!Object.prototype.hasOwnProperty.call(unreadPropStyle, key)) {
continue;
}
var styleValue = unreadPropStyle[key];
if (typeof styleValue === 'number') {
if (!dirty) {
dirty = true;
someDirty = true;
currentStyles[i] = _extends({}, currentStyles[i]);
currentVelocities[i] = _extends({}, currentVelocities[i]);
lastIdealStyles[i] = _extends({}, lastIdealStyles[i]);
lastIdealVelocities[i] = _extends({}, lastIdealVelocities[i]);
}
currentStyles[i][key] = styleValue;
currentVelocities[i][key] = 0;
lastIdealStyles[i][key] = styleValue;
lastIdealVelocities[i][key] = 0;
}
}
}
if (someDirty) {
_this.setState({ currentStyles: currentStyles, currentVelocities: currentVelocities, lastIdealStyles: lastIdealStyles, lastIdealVelocities: lastIdealVelocities });
}
};
this.startAnimationIfNecessary = function () {
// TODO: when config is {a: 10} and dest is {a: 10} do we raf once and
// call cb? No, otherwise accidental parent rerender causes cb trigger
_this.animationID = _raf2['default'](function (timestamp) {
var destStyles = _this.props.styles(_this.state.lastIdealStyles);
// check if we need to animate in the first place
if (shouldStopAnimationAll(_this.state.currentStyles, destStyles, _this.state.currentVelocities)) {
// no need to cancel animationID here; shouldn't have any in flight
_this.animationID = null;
_this.accumulatedTime = 0;
return;
}
var currentTime = timestamp || _performanceNow2['default']();
var timeDelta = currentTime - _this.prevTime;
_this.prevTime = currentTime;
_this.accumulatedTime = _this.accumulatedTime + timeDelta;
// more than 10 frames? prolly switched browser tab. Restart
if (_this.accumulatedTime > msPerFrame * 10) {
_this.accumulatedTime = 0;
}
if (_this.accumulatedTime === 0) {
// no need to cancel animationID here; shouldn't have any in flight
_this.animationID = null;
_this.startAnimationIfNecessary();
return;
}
var currentFrameCompletion = (_this.accumulatedTime - Math.floor(_this.accumulatedTime / msPerFrame) * msPerFrame) / msPerFrame;
var framesToCatchUp = Math.floor(_this.accumulatedTime / msPerFrame);
var newLastIdealStyles = [];
var newLastIdealVelocities = [];
var newCurrentStyles = [];
var newCurrentVelocities = [];
for (var i = 0; i < destStyles.length; i++) {
var destStyle = destStyles[i];
var newCurrentStyle = {};
var newCurrentVelocity = {};
var newLastIdealStyle = {};
var newLastIdealVelocity = {};
for (var key in destStyle) {
if (!Object.prototype.hasOwnProperty.call(destStyle, key)) {
continue;
}
var styleValue = destStyle[key];
if (typeof styleValue === 'number') {
newCurrentStyle[key] = styleValue;
newCurrentVelocity[key] = 0;
newLastIdealStyle[key] = styleValue;
newLastIdealVelocity[key] = 0;
} else {
var newLastIdealStyleValue = _this.state.lastIdealStyles[i][key];
var newLastIdealVelocityValue = _this.state.lastIdealVelocities[i][key];
for (var j = 0; j < framesToCatchUp; j++) {
var _stepper = _stepper4['default'](msPerFrame / 1000, newLastIdealStyleValue, newLastIdealVelocityValue, styleValue.val, styleValue.stiffness, styleValue.damping, styleValue.precision);
newLastIdealStyleValue = _stepper[0];
newLastIdealVelocityValue = _stepper[1];
}
var _stepper2 = _stepper4['default'](msPerFrame / 1000, newLastIdealStyleValue, newLastIdealVelocityValue, styleValue.val, styleValue.stiffness, styleValue.damping, styleValue.precision);
var nextIdealX = _stepper2[0];
var nextIdealV = _stepper2[1];
newCurrentStyle[key] = newLastIdealStyleValue + (nextIdealX - newLastIdealStyleValue) * currentFrameCompletion;
newCurrentVelocity[key] = newLastIdealVelocityValue + (nextIdealV - newLastIdealVelocityValue) * currentFrameCompletion;
newLastIdealStyle[key] = newLastIdealStyleValue;
newLastIdealVelocity[key] = newLastIdealVelocityValue;
}
}
newCurrentStyles[i] = newCurrentStyle;
newCurrentVelocities[i] = newCurrentVelocity;
newLastIdealStyles[i] = newLastIdealStyle;
newLastIdealVelocities[i] = newLastIdealVelocity;
}
_this.animationID = null;
// the amount we're looped over above
_this.accumulatedTime -= framesToCatchUp * msPerFrame;
_this.setState({
currentStyles: newCurrentStyles,
currentVelocities: newCurrentVelocities,
lastIdealStyles: newLastIdealStyles,
lastIdealVelocities: newLastIdealVelocities
});
_this.unreadPropStyles = null;
_this.startAnimationIfNecessary();
});
};
this.state = this.defaultState();
}
StaggeredMotion.prototype.defaultState = function defaultState() {
var _props = this.props;
var defaultStyles = _props.defaultStyles;
var styles = _props.styles;
var currentStyles = defaultStyles || styles().map(_stripStyle2['default']);
var currentVelocities = currentStyles.map(function (currentStyle) {
return _mapToZero2['default'](currentStyle);
});
return {
currentStyles: currentStyles,
currentVelocities: currentVelocities,
lastIdealStyles: currentStyles,
lastIdealVelocities: currentVelocities
};
};
StaggeredMotion.prototype.componentDidMount = function componentDidMount() {
this.prevTime = _performanceNow2['default']();
this.startAnimationIfNecessary();
};
StaggeredMotion.prototype.componentWillReceiveProps = function componentWillReceiveProps(props) {
if (this.unreadPropStyles != null) {
// previous props haven't had the chance to be set yet; set them here
this.clearUnreadPropStyle(this.unreadPropStyles);
}
this.unreadPropStyles = props.styles(this.state.lastIdealStyles);
if (this.animationID == null) {
this.prevTime = _performanceNow2['default']();
this.startAnimationIfNecessary();
}
};
StaggeredMotion.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.animationID != null) {
_raf2['default'].cancel(this.animationID);
this.animationID = null;
}
};
StaggeredMotion.prototype.render = function render() {
var renderedChildren = this.props.children(this.state.currentStyles);
return renderedChildren && _react2['default'].Children.only(renderedChildren);
};
return StaggeredMotion;
})(_react2['default'].Component);
exports['default'] = StaggeredMotion;
module.exports = exports['default'];
// it's possible that currentStyle's value is stale: if props is immediately
// changed from 0 to 400 to spring(0) again, the async currentStyle is still
// at 0 (didn't have time to tick and interpolate even once). If we naively
// compare currentStyle with destVal it'll be 0 === 0 (no animation, stop).
// In reality currentStyle should be 400
// after checking for unreadPropStyles != null, we manually go set the
// non-interpolating values (those that are a number, without a spring
// config)
/***/ }),
/* 249 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _mapToZero = __webpack_require__(242);
var _mapToZero2 = _interopRequireDefault(_mapToZero);
var _stripStyle = __webpack_require__(243);
var _stripStyle2 = _interopRequireDefault(_stripStyle);
var _stepper3 = __webpack_require__(244);
var _stepper4 = _interopRequireDefault(_stepper3);
var _mergeDiff = __webpack_require__(250);
var _mergeDiff2 = _interopRequireDefault(_mergeDiff);
var _performanceNow = __webpack_require__(245);
var _performanceNow2 = _interopRequireDefault(_performanceNow);
var _raf = __webpack_require__(246);
var _raf2 = _interopRequireDefault(_raf);
var _shouldStopAnimation = __webpack_require__(247);
var _shouldStopAnimation2 = _interopRequireDefault(_shouldStopAnimation);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var msPerFrame = 1000 / 60;
// the children function & (potential) styles function asks as param an
// Array<TransitionPlainStyle>, where each TransitionPlainStyle is of the format
// {key: string, data?: any, style: PlainStyle}. However, the way we keep
// internal states doesn't contain such a data structure (check the state and
// TransitionMotionState). So when children function and others ask for such
// data we need to generate them on the fly by combining mergedPropsStyles and
// currentStyles/lastIdealStyles
function rehydrateStyles(mergedPropsStyles, unreadPropStyles, plainStyles) {
// Copy the value to a `const` so that Flow understands that the const won't
// change and will be non-nullable in the callback below.
var cUnreadPropStyles = unreadPropStyles;
if (cUnreadPropStyles == null) {
return mergedPropsStyles.map(function (mergedPropsStyle, i) {
return {
key: mergedPropsStyle.key,
data: mergedPropsStyle.data,
style: plainStyles[i]
};
});
}
return mergedPropsStyles.map(function (mergedPropsStyle, i) {
for (var j = 0; j < cUnreadPropStyles.length; j++) {
if (cUnreadPropStyles[j].key === mergedPropsStyle.key) {
return {
key: cUnreadPropStyles[j].key,
data: cUnreadPropStyles[j].data,
style: plainStyles[i]
};
}
}
return { key: mergedPropsStyle.key, data: mergedPropsStyle.data, style: plainStyles[i] };
});
}
function shouldStopAnimationAll(currentStyles, destStyles, currentVelocities, mergedPropsStyles) {
if (mergedPropsStyles.length !== destStyles.length) {
return false;
}
for (var i = 0; i < mergedPropsStyles.length; i++) {
if (mergedPropsStyles[i].key !== destStyles[i].key) {
return false;
}
}
// we have the invariant that mergedPropsStyles and
// currentStyles/currentVelocities/last* are synced in terms of cells, see
// mergeAndSync comment for more info
for (var i = 0; i < mergedPropsStyles.length; i++) {
if (!_shouldStopAnimation2['default'](currentStyles[i], destStyles[i].style, currentVelocities[i])) {
return false;
}
}
return true;
}
// core key merging logic
// things to do: say previously merged style is {a, b}, dest style (prop) is {b,
// c}, previous current (interpolating) style is {a, b}
// **invariant**: current[i] corresponds to merged[i] in terms of key
// steps:
// turn merged style into {a?, b, c}
// add c, value of c is destStyles.c
// maybe remove a, aka call willLeave(a), then merged is either {b, c} or {a, b, c}
// turn current (interpolating) style from {a, b} into {a?, b, c}
// maybe remove a
// certainly add c, value of c is willEnter(c)
// loop over merged and construct new current
// dest doesn't change, that's owner's
function mergeAndSync(willEnter, willLeave, didLeave, oldMergedPropsStyles, destStyles, oldCurrentStyles, oldCurrentVelocities, oldLastIdealStyles, oldLastIdealVelocities) {
var newMergedPropsStyles = _mergeDiff2['default'](oldMergedPropsStyles, destStyles, function (oldIndex, oldMergedPropsStyle) {
var leavingStyle = willLeave(oldMergedPropsStyle);
if (leavingStyle == null) {
didLeave({ key: oldMergedPropsStyle.key, data: oldMergedPropsStyle.data });
return null;
}
if (_shouldStopAnimation2['default'](oldCurrentStyles[oldIndex], leavingStyle, oldCurrentVelocities[oldIndex])) {
didLeave({ key: oldMergedPropsStyle.key, data: oldMergedPropsStyle.data });
return null;
}
return { key: oldMergedPropsStyle.key, data: oldMergedPropsStyle.data, style: leavingStyle };
});
var newCurrentStyles = [];
var newCurrentVelocities = [];
var newLastIdealStyles = [];
var newLastIdealVelocities = [];
for (var i = 0; i < newMergedPropsStyles.length; i++) {
var newMergedPropsStyleCell = newMergedPropsStyles[i];
var foundOldIndex = null;
for (var j = 0; j < oldMergedPropsStyles.length; j++) {
if (oldMergedPropsStyles[j].key === newMergedPropsStyleCell.key) {
foundOldIndex = j;
break;
}
}
// TODO: key search code
if (foundOldIndex == null) {
var plainStyle = willEnter(newMergedPropsStyleCell);
newCurrentStyles[i] = plainStyle;
newLastIdealStyles[i] = plainStyle;
var velocity = _mapToZero2['default'](newMergedPropsStyleCell.style);
newCurrentVelocities[i] = velocity;
newLastIdealVelocities[i] = velocity;
} else {
newCurrentStyles[i] = oldCurrentStyles[foundOldIndex];
newLastIdealStyles[i] = oldLastIdealStyles[foundOldIndex];
newCurrentVelocities[i] = oldCurrentVelocities[foundOldIndex];
newLastIdealVelocities[i] = oldLastIdealVelocities[foundOldIndex];
}
}
return [newMergedPropsStyles, newCurrentStyles, newCurrentVelocities, newLastIdealStyles, newLastIdealVelocities];
}
var TransitionMotion = (function (_React$Component) {
_inherits(TransitionMotion, _React$Component);
_createClass(TransitionMotion, null, [{
key: 'propTypes',
value: {
defaultStyles: _propTypes2['default'].arrayOf(_propTypes2['default'].shape({
key: _propTypes2['default'].string.isRequired,
data: _propTypes2['default'].any,
style: _propTypes2['default'].objectOf(_propTypes2['default'].number).isRequired
})),
styles: _propTypes2['default'].oneOfType([_propTypes2['default'].func, _propTypes2['default'].arrayOf(_propTypes2['default'].shape({
key: _propTypes2['default'].string.isRequired,
data: _propTypes2['default'].any,
style: _propTypes2['default'].objectOf(_propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].object])).isRequired
}))]).isRequired,
children: _propTypes2['default'].func.isRequired,
willEnter: _propTypes2['default'].func,
willLeave: _propTypes2['default'].func,
didLeave: _propTypes2['default'].func
},
enumerable: true
}, {
key: 'defaultProps',
value: {
willEnter: function willEnter(styleThatEntered) {
return _stripStyle2['default'](styleThatEntered.style);
},
// recall: returning null makes the current unmounting TransitionStyle
// disappear immediately
willLeave: function willLeave() {
return null;
},
didLeave: function didLeave() {}
},
enumerable: true
}]);
function TransitionMotion(props) {
var _this = this;
_classCallCheck(this, TransitionMotion);
_React$Component.call(this, props);
this.unmounting = false;
this.animationID = null;
this.prevTime = 0;
this.accumulatedTime = 0;
this.unreadPropStyles = null;
this.clearUnreadPropStyle = function (unreadPropStyles) {
var _mergeAndSync = mergeAndSync(_this.props.willEnter, _this.props.willLeave, _this.props.didLeave, _this.state.mergedPropsStyles, unreadPropStyles, _this.state.currentStyles, _this.state.currentVelocities, _this.state.lastIdealStyles, _this.state.lastIdealVelocities);
var mergedPropsStyles = _mergeAndSync[0];
var currentStyles = _mergeAndSync[1];
var currentVelocities = _mergeAndSync[2];
var lastIdealStyles = _mergeAndSync[3];
var lastIdealVelocities = _mergeAndSync[4];
for (var i = 0; i < unreadPropStyles.length; i++) {
var unreadPropStyle = unreadPropStyles[i].style;
var dirty = false;
for (var key in unreadPropStyle) {
if (!Object.prototype.hasOwnProperty.call(unreadPropStyle, key)) {
continue;
}
var styleValue = unreadPropStyle[key];
if (typeof styleValue === 'number') {
if (!dirty) {
dirty = true;
currentStyles[i] = _extends({}, currentStyles[i]);
currentVelocities[i] = _extends({}, currentVelocities[i]);
lastIdealStyles[i] = _extends({}, lastIdealStyles[i]);
lastIdealVelocities[i] = _extends({}, lastIdealVelocities[i]);
mergedPropsStyles[i] = {
key: mergedPropsStyles[i].key,
data: mergedPropsStyles[i].data,
style: _extends({}, mergedPropsStyles[i].style)
};
}
currentStyles[i][key] = styleValue;
currentVelocities[i][key] = 0;
lastIdealStyles[i][key] = styleValue;
lastIdealVelocities[i][key] = 0;
mergedPropsStyles[i].style[key] = styleValue;
}
}
}
// unlike the other 2 components, we can't detect staleness and optionally
// opt out of setState here. each style object's data might contain new
// stuff we're not/cannot compare
_this.setState({
currentStyles: currentStyles,
currentVelocities: currentVelocities,
mergedPropsStyles: mergedPropsStyles,
lastIdealStyles: lastIdealStyles,
lastIdealVelocities: lastIdealVelocities
});
};
this.startAnimationIfNecessary = function () {
if (_this.unmounting) {
return;
}
// TODO: when config is {a: 10} and dest is {a: 10} do we raf once and
// call cb? No, otherwise accidental parent rerender causes cb trigger
_this.animationID = _raf2['default'](function (timestamp) {
// https://github.com/chenglou/react-motion/pull/420
// > if execution passes the conditional if (this.unmounting), then
// executes async defaultRaf and after that component unmounts and after
// that the callback of defaultRaf is called, then setState will be called
// on unmounted component.
if (_this.unmounting) {
return;
}
var propStyles = _this.props.styles;
var destStyles = typeof propStyles === 'function' ? propStyles(rehydrateStyles(_this.state.mergedPropsStyles, _this.unreadPropStyles, _this.state.lastIdealStyles)) : propStyles;
// check if we need to animate in the first place
if (shouldStopAnimationAll(_this.state.currentStyles, destStyles, _this.state.currentVelocities, _this.state.mergedPropsStyles)) {
// no need to cancel animationID here; shouldn't have any in flight
_this.animationID = null;
_this.accumulatedTime = 0;
return;
}
var currentTime = timestamp || _performanceNow2['default']();
var timeDelta = currentTime - _this.prevTime;
_this.prevTime = currentTime;
_this.accumulatedTime = _this.accumulatedTime + timeDelta;
// more than 10 frames? prolly switched browser tab. Restart
if (_this.accumulatedTime > msPerFrame * 10) {
_this.accumulatedTime = 0;
}
if (_this.accumulatedTime === 0) {
// no need to cancel animationID here; shouldn't have any in flight
_this.animationID = null;
_this.startAnimationIfNecessary();
return;
}
var currentFrameCompletion = (_this.accumulatedTime - Math.floor(_this.accumulatedTime / msPerFrame) * msPerFrame) / msPerFrame;
var framesToCatchUp = Math.floor(_this.accumulatedTime / msPerFrame);
var _mergeAndSync2 = mergeAndSync(_this.props.willEnter, _this.props.willLeave, _this.props.didLeave, _this.state.mergedPropsStyles, destStyles, _this.state.currentStyles, _this.state.currentVelocities, _this.state.lastIdealStyles, _this.state.lastIdealVelocities);
var newMergedPropsStyles = _mergeAndSync2[0];
var newCurrentStyles = _mergeAndSync2[1];
var newCurrentVelocities = _mergeAndSync2[2];
var newLastIdealStyles = _mergeAndSync2[3];
var newLastIdealVelocities = _mergeAndSync2[4];
for (var i = 0; i < newMergedPropsStyles.length; i++) {
var newMergedPropsStyle = newMergedPropsStyles[i].style;
var newCurrentStyle = {};
var newCurrentVelocity = {};
var newLastIdealStyle = {};
var newLastIdealVelocity = {};
for (var key in newMergedPropsStyle) {
if (!Object.prototype.hasOwnProperty.call(newMergedPropsStyle, key)) {
continue;
}
var styleValue = newMergedPropsStyle[key];
if (typeof styleValue === 'number') {
newCurrentStyle[key] = styleValue;
newCurrentVelocity[key] = 0;
newLastIdealStyle[key] = styleValue;
newLastIdealVelocity[key] = 0;
} else {
var newLastIdealStyleValue = newLastIdealStyles[i][key];
var newLastIdealVelocityValue = newLastIdealVelocities[i][key];
for (var j = 0; j < framesToCatchUp; j++) {
var _stepper = _stepper4['default'](msPerFrame / 1000, newLastIdealStyleValue, newLastIdealVelocityValue, styleValue.val, styleValue.stiffness, styleValue.damping, styleValue.precision);
newLastIdealStyleValue = _stepper[0];
newLastIdealVelocityValue = _stepper[1];
}
var _stepper2 = _stepper4['default'](msPerFrame / 1000, newLastIdealStyleValue, newLastIdealVelocityValue, styleValue.val, styleValue.stiffness, styleValue.damping, styleValue.precision);
var nextIdealX = _stepper2[0];
var nextIdealV = _stepper2[1];
newCurrentStyle[key] = newLastIdealStyleValue + (nextIdealX - newLastIdealStyleValue) * currentFrameCompletion;
newCurrentVelocity[key] = newLastIdealVelocityValue + (nextIdealV - newLastIdealVelocityValue) * currentFrameCompletion;
newLastIdealStyle[key] = newLastIdealStyleValue;
newLastIdealVelocity[key] = newLastIdealVelocityValue;
}
}
newLastIdealStyles[i] = newLastIdealStyle;
newLastIdealVelocities[i] = newLastIdealVelocity;
newCurrentStyles[i] = newCurrentStyle;
newCurrentVelocities[i] = newCurrentVelocity;
}
_this.animationID = null;
// the amount we're looped over above
_this.accumulatedTime -= framesToCatchUp * msPerFrame;
_this.setState({
currentStyles: newCurrentStyles,
currentVelocities: newCurrentVelocities,
lastIdealStyles: newLastIdealStyles,
lastIdealVelocities: newLastIdealVelocities,
mergedPropsStyles: newMergedPropsStyles
});
_this.unreadPropStyles = null;
_this.startAnimationIfNecessary();
});
};
this.state = this.defaultState();
}
TransitionMotion.prototype.defaultState = function defaultState() {
var _props = this.props;
var defaultStyles = _props.defaultStyles;
var styles = _props.styles;
var willEnter = _props.willEnter;
var willLeave = _props.willLeave;
var didLeave = _props.didLeave;
var destStyles = typeof styles === 'function' ? styles(defaultStyles) : styles;
// this is special. for the first time around, we don't have a comparison
// between last (no last) and current merged props. we'll compute last so:
// say default is {a, b} and styles (dest style) is {b, c}, we'll
// fabricate last as {a, b}
var oldMergedPropsStyles = undefined;
if (defaultStyles == null) {
oldMergedPropsStyles = destStyles;
} else {
oldMergedPropsStyles = defaultStyles.map(function (defaultStyleCell) {
// TODO: key search code
for (var i = 0; i < destStyles.length; i++) {
if (destStyles[i].key === defaultStyleCell.key) {
return destStyles[i];
}
}
return defaultStyleCell;
});
}
var oldCurrentStyles = defaultStyles == null ? destStyles.map(function (s) {
return _stripStyle2['default'](s.style);
}) : defaultStyles.map(function (s) {
return _stripStyle2['default'](s.style);
});
var oldCurrentVelocities = defaultStyles == null ? destStyles.map(function (s) {
return _mapToZero2['default'](s.style);
}) : defaultStyles.map(function (s) {
return _mapToZero2['default'](s.style);
});
var _mergeAndSync3 = mergeAndSync(
// Because this is an old-style createReactClass component, Flow doesn't
// understand that the willEnter and willLeave props have default values
// and will always be present.
willEnter, willLeave, didLeave, oldMergedPropsStyles, destStyles, oldCurrentStyles, oldCurrentVelocities, oldCurrentStyles, // oldLastIdealStyles really
oldCurrentVelocities);
var mergedPropsStyles = _mergeAndSync3[0];
var currentStyles = _mergeAndSync3[1];
var currentVelocities = _mergeAndSync3[2];
var lastIdealStyles = _mergeAndSync3[3];
var lastIdealVelocities = _mergeAndSync3[4];
// oldLastIdealVelocities really
return {
currentStyles: currentStyles,
currentVelocities: currentVelocities,
lastIdealStyles: lastIdealStyles,
lastIdealVelocities: lastIdealVelocities,
mergedPropsStyles: mergedPropsStyles
};
};
// after checking for unreadPropStyles != null, we manually go set the
// non-interpolating values (those that are a number, without a spring
// config)
TransitionMotion.prototype.componentDidMount = function componentDidMount() {
this.prevTime = _performanceNow2['default']();
this.startAnimationIfNecessary();
};
TransitionMotion.prototype.componentWillReceiveProps = function componentWillReceiveProps(props) {
if (this.unreadPropStyles) {
// previous props haven't had the chance to be set yet; set them here
this.clearUnreadPropStyle(this.unreadPropStyles);
}
var styles = props.styles;
if (typeof styles === 'function') {
this.unreadPropStyles = styles(rehydrateStyles(this.state.mergedPropsStyles, this.unreadPropStyles, this.state.lastIdealStyles));
} else {
this.unreadPropStyles = styles;
}
if (this.animationID == null) {
this.prevTime = _performanceNow2['default']();
this.startAnimationIfNecessary();
}
};
TransitionMotion.prototype.componentWillUnmount = function componentWillUnmount() {
this.unmounting = true;
if (this.animationID != null) {
_raf2['default'].cancel(this.animationID);
this.animationID = null;
}
};
TransitionMotion.prototype.render = function render() {
var hydratedStyles = rehydrateStyles(this.state.mergedPropsStyles, this.unreadPropStyles, this.state.currentStyles);
var renderedChildren = this.props.children(hydratedStyles);
return renderedChildren && _react2['default'].Children.only(renderedChildren);
};
return TransitionMotion;
})(_react2['default'].Component);
exports['default'] = TransitionMotion;
module.exports = exports['default'];
// list of styles, each containing interpolating values. Part of what's passed
// to children function. Notice that this is
// Array<ActualInterpolatingStyleObject>, without the wrapper that is {key: ...,
// data: ... style: ActualInterpolatingStyleObject}. Only mergedPropsStyles
// contains the key & data info (so that we only have a single source of truth
// for these, and to save space). Check the comment for `rehydrateStyles` to
// see how we regenerate the entirety of what's passed to children function
// the array that keeps track of currently rendered stuff! Including stuff
// that you've unmounted but that's still animating. This is where it lives
// it's possible that currentStyle's value is stale: if props is immediately
// changed from 0 to 400 to spring(0) again, the async currentStyle is still
// at 0 (didn't have time to tick and interpolate even once). If we naively
// compare currentStyle with destVal it'll be 0 === 0 (no animation, stop).
// In reality currentStyle should be 400
/***/ }),
/* 250 */
/***/ (function(module, exports) {
// core keys merging algorithm. If previous render's keys are [a, b], and the
// next render's [c, b, d], what's the final merged keys and ordering?
// - c and a must both be before b
// - b before d
// - ordering between a and c ambiguous
// this reduces to merging two partially ordered lists (e.g. lists where not
// every item has a definite ordering, like comparing a and c above). For the
// ambiguous ordering we deterministically choose to place the next render's
// item after the previous'; so c after a
// this is called a topological sorting. Except the existing algorithms don't
// work well with js bc of the amount of allocation, and isn't optimized for our
// current use-case bc the runtime is linear in terms of edges (see wiki for
// meaning), which is huge when two lists have many common elements
'use strict';
exports.__esModule = true;
exports['default'] = mergeDiff;
function mergeDiff(prev, next, onRemove) {
// bookkeeping for easier access of a key's index below. This is 2 allocations +
// potentially triggering chrome hash map mode for objs (so it might be faster
var prevKeyIndex = {};
for (var i = 0; i < prev.length; i++) {
prevKeyIndex[prev[i].key] = i;
}
var nextKeyIndex = {};
for (var i = 0; i < next.length; i++) {
nextKeyIndex[next[i].key] = i;
}
// first, an overly elaborate way of merging prev and next, eliminating
// duplicates (in terms of keys). If there's dupe, keep the item in next).
// This way of writing it saves allocations
var ret = [];
for (var i = 0; i < next.length; i++) {
ret[i] = next[i];
}
for (var i = 0; i < prev.length; i++) {
if (!Object.prototype.hasOwnProperty.call(nextKeyIndex, prev[i].key)) {
// this is called my TM's `mergeAndSync`, which calls willLeave. We don't
// merge in keys that the user desires to kill
var fill = onRemove(i, prev[i]);
if (fill != null) {
ret.push(fill);
}
}
}
// now all the items all present. Core sorting logic to have the right order
return ret.sort(function (a, b) {
var nextOrderA = nextKeyIndex[a.key];
var nextOrderB = nextKeyIndex[b.key];
var prevOrderA = prevKeyIndex[a.key];
var prevOrderB = prevKeyIndex[b.key];
if (nextOrderA != null && nextOrderB != null) {
// both keys in next
return nextKeyIndex[a.key] - nextKeyIndex[b.key];
} else if (prevOrderA != null && prevOrderB != null) {
// both keys in prev
return prevKeyIndex[a.key] - prevKeyIndex[b.key];
} else if (nextOrderA != null) {
// key a in next, key b in prev
// how to determine the order between a and b? We find a "pivot" (term
// abuse), a key present in both prev and next, that is sandwiched between
// a and b. In the context of our above example, if we're comparing a and
// d, b's (the only) pivot
for (var i = 0; i < next.length; i++) {
var pivot = next[i].key;
if (!Object.prototype.hasOwnProperty.call(prevKeyIndex, pivot)) {
continue;
}
if (nextOrderA < nextKeyIndex[pivot] && prevOrderB > prevKeyIndex[pivot]) {
return -1;
} else if (nextOrderA > nextKeyIndex[pivot] && prevOrderB < prevKeyIndex[pivot]) {
return 1;
}
}
// pluggable. default to: next bigger than prev
return 1;
}
// prevOrderA, nextOrderB
for (var i = 0; i < next.length; i++) {
var pivot = next[i].key;
if (!Object.prototype.hasOwnProperty.call(prevKeyIndex, pivot)) {
continue;
}
if (nextOrderB < nextKeyIndex[pivot] && prevOrderA > prevKeyIndex[pivot]) {
return 1;
} else if (nextOrderB > nextKeyIndex[pivot] && prevOrderA < prevKeyIndex[pivot]) {
return -1;
}
}
// pluggable. default to: next bigger than prev
return -1;
});
}
module.exports = exports['default'];
// to loop through and find a key's index each time), but I no longer care
/***/ }),
/* 251 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = spring;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _presets = __webpack_require__(252);
var _presets2 = _interopRequireDefault(_presets);
var defaultConfig = _extends({}, _presets2['default'].noWobble, {
precision: 0.01
});
function spring(val, config) {
return _extends({}, defaultConfig, config, { val: val });
}
module.exports = exports['default'];
/***/ }),
/* 252 */
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = {
noWobble: { stiffness: 170, damping: 26 }, // the default, if nothing provided
gentle: { stiffness: 120, damping: 14 },
wobbly: { stiffness: 180, damping: 12 },
stiff: { stiffness: 210, damping: 20 }
};
module.exports = exports["default"];
/***/ }),
/* 253 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
exports.__esModule = true;
exports['default'] = reorderKeys;
var hasWarned = false;
function reorderKeys() {
if (process.env.NODE_ENV === 'development') {
if (!hasWarned) {
hasWarned = true;
console.error('`reorderKeys` has been removed, since it is no longer needed for TransitionMotion\'s new styles array API.');
}
}
}
module.exports = exports['default'];
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 254 */
/***/ (function(module, exports, __webpack_require__) {
(function (global, factory) {
true ? module.exports = factory(__webpack_require__(2), __webpack_require__(1)) :
typeof define === 'function' && define.amd ? define(['react-dom', 'react'], factory) :
(global.ReactDraggable = factory(global.ReactDOM,global.React));
}(this, (function (ReactDOM,React) { 'use strict';
ReactDOM = ReactDOM && ReactDOM.hasOwnProperty('default') ? ReactDOM['default'] : ReactDOM;
React = React && React.hasOwnProperty('default') ? React['default'] : React;
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
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;
};
var emptyFunction_1 = emptyFunction;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/**
* 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) {};
{
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;
}
}
var invariant_1 = invariant;
/**
* 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_1;
{
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));
}
};
}
var warning_1 = warning;
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* 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;
}
}
var objectAssign = 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;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
{
var invariant$1 = invariant_1;
var warning$1 = warning_1;
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
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) {
{
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$1(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
warning$1(!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$1(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
var checkPropTypes_1 = checkPropTypes;
var factoryWithTypeCheckers = 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 = '<<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,
exact: createStrictShapeTypeChecker,
};
/**
* 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) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
invariant_1(
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 ("development" !== 'production' && typeof console !== 'undefined') {
// 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_1(
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_1.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_1);
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)) {
warning_1(false, 'Invalid argument supplied to oneOf, expected an instance of array.');
return emptyFunction_1.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_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
warning_1(false, 'Invalid argument supplied to oneOfType, expected an instance of array.');
return emptyFunction_1.thatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
warning_1(
false,
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received %s at index %s.',
getPostfixForTypeWarning(checker),
i
);
return emptyFunction_1.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_1) == 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_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(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`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
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_1;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(isValidElement, throwOnDirectAccess);
}
});
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if ('object' !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (false) {
// register as 'classnames', consistent with npm package name
undefined('classnames', [], function () {
return classNames;
});
} else {
window.classNames = classNames;
}
}());
});
// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc
function findInArray(array /*: Array<any> | TouchList*/, callback /*: Function*/) /*: any*/ {
for (var i = 0, length = array.length; i < length; i++) {
if (callback.apply(callback, [array[i], i, array])) return array[i];
}
}
function isFunction(func /*: any*/) /*: boolean*/ {
return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';
}
function isNum(num /*: any*/) /*: boolean*/ {
return typeof num === 'number' && !isNaN(num);
}
function int(a /*: string*/) /*: number*/ {
return parseInt(a, 10);
}
function dontSetMe(props /*: Object*/, propName /*: string*/, componentName /*: string*/) {
if (props[propName]) {
return new Error('Invalid prop ' + propName + ' passed to ' + componentName + ' - do not set this, set it on the child.');
}
}
var prefixes = ['Moz', 'Webkit', 'O', 'ms'];
function getPrefix() /*: string*/ {
var prop /*: string*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'transform';
// Checking specifically for 'window.document' is for pseudo-browser server-side
// environments that define 'window' as the global context.
// E.g. React-rails (see https://github.com/reactjs/react-rails/pull/84)
if (typeof window === 'undefined' || typeof window.document === 'undefined') return '';
var style = window.document.documentElement.style;
if (prop in style) return '';
for (var i = 0; i < prefixes.length; i++) {
if (browserPrefixToKey(prop, prefixes[i]) in style) return prefixes[i];
}
return '';
}
function browserPrefixToKey(prop /*: string*/, prefix /*: string*/) /*: string*/ {
return prefix ? '' + prefix + kebabToTitleCase(prop) : prop;
}
function kebabToTitleCase(str /*: string*/) /*: string*/ {
var out = '';
var shouldCapitalize = true;
for (var i = 0; i < str.length; i++) {
if (shouldCapitalize) {
out += str[i].toUpperCase();
shouldCapitalize = false;
} else if (str[i] === '-') {
shouldCapitalize = true;
} else {
out += str[i];
}
}
return out;
}
// Default export is the prefix itself, like 'Moz', 'Webkit', etc
// Note that you may have to re-test for certain things; for instance, Chrome 50
// can handle unprefixed `transform`, but not unprefixed `user-select`
var browserPrefix = getPrefix();
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
/*:: import type {ControlPosition, PositionOffsetControlPosition, MouseTouchEvent} from './types';*/
var matchesSelectorFunc = '';
function matchesSelector(el /*: Node*/, selector /*: string*/) /*: boolean*/ {
if (!matchesSelectorFunc) {
matchesSelectorFunc = findInArray(['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'], function (method) {
// $FlowIgnore: Doesn't think elements are indexable
return isFunction(el[method]);
});
}
// Might not be found entirely (not an Element?) - in that case, bail
// $FlowIgnore: Doesn't think elements are indexable
if (!isFunction(el[matchesSelectorFunc])) return false;
// $FlowIgnore: Doesn't think elements are indexable
return el[matchesSelectorFunc](selector);
}
// Works up the tree to the draggable itself attempting to match selector.
function matchesSelectorAndParentsTo(el /*: Node*/, selector /*: string*/, baseNode /*: Node*/) /*: boolean*/ {
var node = el;
do {
if (matchesSelector(node, selector)) return true;
if (node === baseNode) return false;
node = node.parentNode;
} while (node);
return false;
}
function addEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/) /*: void*/ {
if (!el) {
return;
}
if (el.attachEvent) {
el.attachEvent('on' + event, handler);
} else if (el.addEventListener) {
el.addEventListener(event, handler, true);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = handler;
}
}
function removeEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/) /*: void*/ {
if (!el) {
return;
}
if (el.detachEvent) {
el.detachEvent('on' + event, handler);
} else if (el.removeEventListener) {
el.removeEventListener(event, handler, true);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = null;
}
}
function outerHeight(node /*: HTMLElement*/) /*: number*/ {
// This is deliberately excluding margin for our calculations, since we are using
// offsetTop which is including margin. See getBoundPosition
var height = node.clientHeight;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height += int(computedStyle.borderTopWidth);
height += int(computedStyle.borderBottomWidth);
return height;
}
function outerWidth(node /*: HTMLElement*/) /*: number*/ {
// This is deliberately excluding margin for our calculations, since we are using
// offsetLeft which is including margin. See getBoundPosition
var width = node.clientWidth;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width += int(computedStyle.borderLeftWidth);
width += int(computedStyle.borderRightWidth);
return width;
}
function innerHeight(node /*: HTMLElement*/) /*: number*/ {
var height = node.clientHeight;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height -= int(computedStyle.paddingTop);
height -= int(computedStyle.paddingBottom);
return height;
}
function innerWidth(node /*: HTMLElement*/) /*: number*/ {
var width = node.clientWidth;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width -= int(computedStyle.paddingLeft);
width -= int(computedStyle.paddingRight);
return width;
}
// Get from offsetParent
function offsetXYFromParent(evt /*: {clientX: number, clientY: number}*/, offsetParent /*: HTMLElement*/) /*: ControlPosition*/ {
var isBody = offsetParent === offsetParent.ownerDocument.body;
var offsetParentRect = isBody ? { left: 0, top: 0 } : offsetParent.getBoundingClientRect();
var x = evt.clientX + offsetParent.scrollLeft - offsetParentRect.left;
var y = evt.clientY + offsetParent.scrollTop - offsetParentRect.top;
return { x: x, y: y };
}
function createCSSTransform(controlPos /*: ControlPosition*/, positionOffset /*: PositionOffsetControlPosition*/) /*: Object*/ {
var translation = getTranslation(controlPos, positionOffset, 'px');
return defineProperty({}, browserPrefixToKey('transform', browserPrefix), translation);
}
function createSVGTransform(controlPos /*: ControlPosition*/, positionOffset /*: PositionOffsetControlPosition*/) /*: string*/ {
var translation = getTranslation(controlPos, positionOffset, '');
return translation;
}
function getTranslation(_ref2, positionOffset /*: PositionOffsetControlPosition*/, unitSuffix /*: string*/) /*: string*/ {
var x = _ref2.x,
y = _ref2.y;
var translation = 'translate(' + x + unitSuffix + ',' + y + unitSuffix + ')';
if (positionOffset) {
var defaultX = '' + (typeof positionOffset.x === 'string' ? positionOffset.x : positionOffset.x + unitSuffix);
var defaultY = '' + (typeof positionOffset.y === 'string' ? positionOffset.y : positionOffset.y + unitSuffix);
translation = 'translate(' + defaultX + ', ' + defaultY + ')' + translation;
}
return translation;
}
function getTouch(e /*: MouseTouchEvent*/, identifier /*: number*/) /*: ?{clientX: number, clientY: number}*/ {
return e.targetTouches && findInArray(e.targetTouches, function (t) {
return identifier === t.identifier;
}) || e.changedTouches && findInArray(e.changedTouches, function (t) {
return identifier === t.identifier;
});
}
function getTouchIdentifier(e /*: MouseTouchEvent*/) /*: ?number*/ {
if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;
if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;
}
// User-select Hacks:
//
// Useful for preventing blue highlights all over everything when dragging.
// Note we're passing `document` b/c we could be iframed
function addUserSelectStyles(doc /*: ?Document*/) {
if (!doc) return;
var styleEl = doc.getElementById('react-draggable-style-el');
if (!styleEl) {
styleEl = doc.createElement('style');
styleEl.type = 'text/css';
styleEl.id = 'react-draggable-style-el';
styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {background: transparent;}\n';
styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {background: transparent;}\n';
doc.getElementsByTagName('head')[0].appendChild(styleEl);
}
if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');
}
function removeUserSelectStyles(doc /*: ?Document*/) {
try {
if (doc && doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');
// $FlowIgnore: IE
if (doc.selection) {
// $FlowIgnore: IE
doc.selection.empty();
} else {
window.getSelection().removeAllRanges(); // remove selection caused by scroll
}
} catch (e) {
// probably IE
}
}
function styleHacks() /*: Object*/ {
var childStyle /*: Object*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// Workaround IE pointer events; see #51
// https://github.com/mzabriskie/react-draggable/issues/51#issuecomment-103488278
return _extends({
touchAction: 'none'
}, childStyle);
}
function addClassName(el /*: HTMLElement*/, className /*: string*/) {
if (el.classList) {
el.classList.add(className);
} else {
if (!el.className.match(new RegExp('(?:^|\\s)' + className + '(?!\\S)'))) {
el.className += ' ' + className;
}
}
}
function removeClassName(el /*: HTMLElement*/, className /*: string*/) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(?:^|\\s)' + className + '(?!\\S)', 'g'), '');
}
}
/*:: import type Draggable from '../Draggable';*/
/*:: import type {Bounds, ControlPosition, DraggableData, MouseTouchEvent} from './types';*/
/*:: import type DraggableCore from '../DraggableCore';*/
function getBoundPosition(draggable /*: Draggable*/, x /*: number*/, y /*: number*/) /*: [number, number]*/ {
// If no bounds, short-circuit and move on
if (!draggable.props.bounds) return [x, y];
// Clone new bounds
var bounds = draggable.props.bounds;
bounds = typeof bounds === 'string' ? bounds : cloneBounds(bounds);
var node = findDOMNode(draggable);
if (typeof bounds === 'string') {
var ownerDocument = node.ownerDocument;
var ownerWindow = ownerDocument.defaultView;
var boundNode = void 0;
if (bounds === 'parent') {
boundNode = node.parentNode;
} else {
boundNode = ownerDocument.querySelector(bounds);
}
if (!(boundNode instanceof ownerWindow.HTMLElement)) {
throw new Error('Bounds selector "' + bounds + '" could not find an element.');
}
var nodeStyle = ownerWindow.getComputedStyle(node);
var boundNodeStyle = ownerWindow.getComputedStyle(boundNode);
// Compute bounds. This is a pain with padding and offsets but this gets it exactly right.
bounds = {
left: -node.offsetLeft + int(boundNodeStyle.paddingLeft) + int(nodeStyle.marginLeft),
top: -node.offsetTop + int(boundNodeStyle.paddingTop) + int(nodeStyle.marginTop),
right: innerWidth(boundNode) - outerWidth(node) - node.offsetLeft + int(boundNodeStyle.paddingRight) - int(nodeStyle.marginRight),
bottom: innerHeight(boundNode) - outerHeight(node) - node.offsetTop + int(boundNodeStyle.paddingBottom) - int(nodeStyle.marginBottom)
};
}
// Keep x and y below right and bottom limits...
if (isNum(bounds.right)) x = Math.min(x, bounds.right);
if (isNum(bounds.bottom)) y = Math.min(y, bounds.bottom);
// But above left and top limits.
if (isNum(bounds.left)) x = Math.max(x, bounds.left);
if (isNum(bounds.top)) y = Math.max(y, bounds.top);
return [x, y];
}
function snapToGrid(grid /*: [number, number]*/, pendingX /*: number*/, pendingY /*: number*/) /*: [number, number]*/ {
var x = Math.round(pendingX / grid[0]) * grid[0];
var y = Math.round(pendingY / grid[1]) * grid[1];
return [x, y];
}
function canDragX(draggable /*: Draggable*/) /*: boolean*/ {
return draggable.props.axis === 'both' || draggable.props.axis === 'x';
}
function canDragY(draggable /*: Draggable*/) /*: boolean*/ {
return draggable.props.axis === 'both' || draggable.props.axis === 'y';
}
// Get {x, y} positions from event.
function getControlPosition(e /*: MouseTouchEvent*/, touchIdentifier /*: ?number*/, draggableCore /*: DraggableCore*/) /*: ?ControlPosition*/ {
var touchObj = typeof touchIdentifier === 'number' ? getTouch(e, touchIdentifier) : null;
if (typeof touchIdentifier === 'number' && !touchObj) return null; // not the right touch
var node = findDOMNode(draggableCore);
// User can provide an offsetParent if desired.
var offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;
return offsetXYFromParent(touchObj || e, offsetParent);
}
// Create an data object exposed by <DraggableCore>'s events
function createCoreData(draggable /*: DraggableCore*/, x /*: number*/, y /*: number*/) /*: DraggableData*/ {
var state = draggable.state;
var isStart = !isNum(state.lastX);
var node = findDOMNode(draggable);
if (isStart) {
// If this is our first move, use the x and y as last coords.
return {
node: node,
deltaX: 0, deltaY: 0,
lastX: x, lastY: y,
x: x, y: y
};
} else {
// Otherwise calculate proper values.
return {
node: node,
deltaX: x - state.lastX, deltaY: y - state.lastY,
lastX: state.lastX, lastY: state.lastY,
x: x, y: y
};
}
}
// Create an data exposed by <Draggable>'s events
function createDraggableData(draggable /*: Draggable*/, coreData /*: DraggableData*/) /*: DraggableData*/ {
var scale = draggable.props.scale;
return {
node: coreData.node,
x: draggable.state.x + coreData.deltaX / scale,
y: draggable.state.y + coreData.deltaY / scale,
deltaX: coreData.deltaX / scale,
deltaY: coreData.deltaY / scale,
lastX: draggable.state.x,
lastY: draggable.state.y
};
}
// A lot faster than stringify/parse
function cloneBounds(bounds /*: Bounds*/) /*: Bounds*/ {
return {
left: bounds.left,
top: bounds.top,
right: bounds.right,
bottom: bounds.bottom
};
}
function findDOMNode(draggable /*: Draggable | DraggableCore*/) /*: HTMLElement*/ {
var node = ReactDOM.findDOMNode(draggable);
if (!node) {
throw new Error('<DraggableCore>: Unmounted during event!');
}
// $FlowIgnore we can't assert on HTMLElement due to tests... FIXME
return node;
}
/*eslint no-console:0*/
function log() {
}
/*:: import type {EventHandler, MouseTouchEvent} from './utils/types';*/
// Simple abstraction for dragging events names.
/*:: import type {Element as ReactElement} from 'react';*/
var eventsFor = {
touch: {
start: 'touchstart',
move: 'touchmove',
stop: 'touchend'
},
mouse: {
start: 'mousedown',
move: 'mousemove',
stop: 'mouseup'
}
};
// Default to mouse events.
var dragEventFor = eventsFor.mouse;
/*:: type DraggableCoreState = {
dragging: boolean,
lastX: number,
lastY: number,
touchIdentifier: ?number
};*/
/*:: export type DraggableBounds = {
left: number,
right: number,
top: number,
bottom: number,
};*/
/*:: export type DraggableData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number,
};*/
/*:: export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void;*/
/*:: export type ControlPosition = {x: number, y: number};*/
/*:: export type PositionOffsetControlPosition = {x: number|string, y: number|string};*/
//
// Define <DraggableCore>.
//
// <DraggableCore> is for advanced usage of <Draggable>. It maintains minimal internal state so it can
// work well with libraries that require more control over the element.
//
/*:: export type DraggableCoreProps = {
allowAnyClick: boolean,
cancel: string,
children: ReactElement<any>,
disabled: boolean,
enableUserSelectHack: boolean,
offsetParent: HTMLElement,
grid: [number, number],
handle: string,
onStart: DraggableEventHandler,
onDrag: DraggableEventHandler,
onStop: DraggableEventHandler,
onMouseDown: (e: MouseEvent) => void,
};*/
var DraggableCore = function (_React$Component) {
inherits(DraggableCore, _React$Component);
function DraggableCore() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, DraggableCore);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = DraggableCore.__proto__ || Object.getPrototypeOf(DraggableCore)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
dragging: false,
// Used while dragging to determine deltas.
lastX: NaN, lastY: NaN,
touchIdentifier: null
}, _this.handleDragStart = function (e) {
// Make it possible to attach event handlers on top of this one.
_this.props.onMouseDown(e);
// Only accept left-clicks.
if (!_this.props.allowAnyClick && typeof e.button === 'number' && e.button !== 0) return false;
// Get nodes. Be sure to grab relative document (could be iframed)
var thisNode = ReactDOM.findDOMNode(_this);
if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {
throw new Error('<DraggableCore> not mounted on DragStart!');
}
var ownerDocument = thisNode.ownerDocument;
// Short circuit if handle or cancel prop was provided and selector doesn't match.
if (_this.props.disabled || !(e.target instanceof ownerDocument.defaultView.Node) || _this.props.handle && !matchesSelectorAndParentsTo(e.target, _this.props.handle, thisNode) || _this.props.cancel && matchesSelectorAndParentsTo(e.target, _this.props.cancel, thisNode)) {
return;
}
// Set touch identifier in component state if this is a touch event. This allows us to
// distinguish between individual touches on multitouch screens by identifying which
// touchpoint was set to this element.
var touchIdentifier = getTouchIdentifier(e);
_this.setState({ touchIdentifier: touchIdentifier });
// Get the current drag point from the event. This is used as the offset.
var position = getControlPosition(e, touchIdentifier, _this);
if (position == null) return; // not possible but satisfies flow
var x = position.x,
y = position.y;
// Create an event object with all the data parents need to make a decision here.
var coreEvent = createCoreData(_this, x, y);
// Call event handler. If it returns explicit false, cancel.
log('calling', _this.props.onStart);
var shouldUpdate = _this.props.onStart(e, coreEvent);
if (shouldUpdate === false) return;
// Add a style to the body to disable user-select. This prevents text from
// being selected all over the page.
if (_this.props.enableUserSelectHack) addUserSelectStyles(ownerDocument);
// Initiate dragging. Set the current x and y as offsets
// so we know how much we've moved during the drag. This allows us
// to drag elements around even if they have been moved, without issue.
_this.setState({
dragging: true,
lastX: x,
lastY: y
});
// Add events to the document directly so we catch when the user's mouse/touch moves outside of
// this element. We use different events depending on whether or not we have detected that this
// is a touch-capable device.
addEvent(ownerDocument, dragEventFor.move, _this.handleDrag);
addEvent(ownerDocument, dragEventFor.stop, _this.handleDragStop);
}, _this.handleDrag = function (e) {
// Prevent scrolling on mobile devices, like ipad/iphone.
if (e.type === 'touchmove') e.preventDefault();
// Get the current drag point from the event. This is used as the offset.
var position = getControlPosition(e, _this.state.touchIdentifier, _this);
if (position == null) return;
var x = position.x,
y = position.y;
// Snap to grid if prop has been provided
if (Array.isArray(_this.props.grid)) {
var _deltaX = x - _this.state.lastX,
_deltaY = y - _this.state.lastY;
var _snapToGrid = snapToGrid(_this.props.grid, _deltaX, _deltaY);
var _snapToGrid2 = slicedToArray(_snapToGrid, 2);
_deltaX = _snapToGrid2[0];
_deltaY = _snapToGrid2[1];
if (!_deltaX && !_deltaY) return; // skip useless drag
x = _this.state.lastX + _deltaX, y = _this.state.lastY + _deltaY;
}
var coreEvent = createCoreData(_this, x, y);
// Call event handler. If it returns explicit false, trigger end.
var shouldUpdate = _this.props.onDrag(e, coreEvent);
if (shouldUpdate === false) {
try {
// $FlowIgnore
_this.handleDragStop(new MouseEvent('mouseup'));
} catch (err) {
// Old browsers
var event = ((document.createEvent('MouseEvents') /*: any*/) /*: MouseTouchEvent*/);
// I see why this insanity was deprecated
// $FlowIgnore
event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
_this.handleDragStop(event);
}
return;
}
_this.setState({
lastX: x,
lastY: y
});
}, _this.handleDragStop = function (e) {
if (!_this.state.dragging) return;
var position = getControlPosition(e, _this.state.touchIdentifier, _this);
if (position == null) return;
var x = position.x,
y = position.y;
var coreEvent = createCoreData(_this, x, y);
var thisNode = ReactDOM.findDOMNode(_this);
if (thisNode) {
// Remove user-select hack
if (_this.props.enableUserSelectHack) removeUserSelectStyles(thisNode.ownerDocument);
}
// Reset the el.
_this.setState({
dragging: false,
lastX: NaN,
lastY: NaN
});
// Call event handler
_this.props.onStop(e, coreEvent);
if (thisNode) {
removeEvent(thisNode.ownerDocument, dragEventFor.move, _this.handleDrag);
removeEvent(thisNode.ownerDocument, dragEventFor.stop, _this.handleDragStop);
}
}, _this.onMouseDown = function (e) {
dragEventFor = eventsFor.mouse; // on touchscreen laptops we could switch back to mouse
return _this.handleDragStart(e);
}, _this.onMouseUp = function (e) {
dragEventFor = eventsFor.mouse;
return _this.handleDragStop(e);
}, _this.onTouchStart = function (e) {
// We're on a touch device now, so change the event handlers
dragEventFor = eventsFor.touch;
return _this.handleDragStart(e);
}, _this.onTouchEnd = function (e) {
// We're on a touch device now, so change the event handlers
dragEventFor = eventsFor.touch;
return _this.handleDragStop(e);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(DraggableCore, [{
key: 'componentWillUnmount',
value: function componentWillUnmount() {
// Remove any leftover event handlers. Remove both touch and mouse handlers in case
// some browser quirk caused a touch event to fire during a mouse move, or vice versa.
var thisNode = ReactDOM.findDOMNode(this);
if (thisNode) {
var ownerDocument = thisNode.ownerDocument;
removeEvent(ownerDocument, eventsFor.mouse.move, this.handleDrag);
removeEvent(ownerDocument, eventsFor.touch.move, this.handleDrag);
removeEvent(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);
removeEvent(ownerDocument, eventsFor.touch.stop, this.handleDragStop);
if (this.props.enableUserSelectHack) removeUserSelectStyles(ownerDocument);
}
}
// Same as onMouseDown (start drag), but now consider this a touch device.
}, {
key: 'render',
value: function render() {
// Reuse the child provided
// This makes it flexible to use whatever element is wanted (div, ul, etc)
return React.cloneElement(React.Children.only(this.props.children), {
style: styleHacks(this.props.children.props.style),
// Note: mouseMove handler is attached to document so it will still function
// when the user drags quickly and leaves the bounds of the element.
onMouseDown: this.onMouseDown,
onTouchStart: this.onTouchStart,
onMouseUp: this.onMouseUp,
onTouchEnd: this.onTouchEnd
});
}
}]);
return DraggableCore;
}(React.Component);
DraggableCore.displayName = 'DraggableCore';
DraggableCore.propTypes = {
/**
* `allowAnyClick` allows dragging using any mouse button.
* By default, we only accept the left button.
*
* Defaults to `false`.
*/
allowAnyClick: propTypes.bool,
/**
* `disabled`, if true, stops the <Draggable> from dragging. All handlers,
* with the exception of `onMouseDown`, will not fire.
*/
disabled: propTypes.bool,
/**
* By default, we add 'user-select:none' attributes to the document body
* to prevent ugly text selection during drag. If this is causing problems
* for your app, set this to `false`.
*/
enableUserSelectHack: propTypes.bool,
/**
* `offsetParent`, if set, uses the passed DOM node to compute drag offsets
* instead of using the parent node.
*/
offsetParent: function offsetParent(props /*: DraggableCoreProps*/, propName /*: $Keys<DraggableCoreProps>*/) {
if (props[propName] && props[propName].nodeType !== 1) {
throw new Error('Draggable\'s offsetParent must be a DOM Node.');
}
},
/**
* `grid` specifies the x and y that dragging should snap to.
*/
grid: propTypes.arrayOf(propTypes.number),
/**
* `scale` specifies the scale of the area you are dragging inside of. It allows
* the drag deltas to scale correctly with how far zoomed in/out you are.
*/
scale: propTypes.number,
/**
* `handle` specifies a selector to be used as the handle that initiates drag.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable handle=".handle">
* <div>
* <div className="handle">Click me to drag</div>
* <div>This is some other content</div>
* </div>
* </Draggable>
* );
* }
* });
* ```
*/
handle: propTypes.string,
/**
* `cancel` specifies a selector to be used to prevent drag initialization.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return(
* <Draggable cancel=".cancel">
* <div>
* <div className="cancel">You can't drag from here</div>
* <div>Dragging here works fine</div>
* </div>
* </Draggable>
* );
* }
* });
* ```
*/
cancel: propTypes.string,
/**
* Called when dragging starts.
* If this function returns the boolean false, dragging will be canceled.
*/
onStart: propTypes.func,
/**
* Called while dragging.
* If this function returns the boolean false, dragging will be canceled.
*/
onDrag: propTypes.func,
/**
* Called when dragging stops.
* If this function returns the boolean false, the drag will remain active.
*/
onStop: propTypes.func,
/**
* A workaround option which can be passed if onMouseDown needs to be accessed,
* since it'll always be blocked (as there is internal use of onMouseDown)
*/
onMouseDown: propTypes.func,
/**
* These properties should be defined on the child, not here.
*/
className: dontSetMe,
style: dontSetMe,
transform: dontSetMe
};
DraggableCore.defaultProps = {
allowAnyClick: false, // by default only accept left click
cancel: null,
disabled: false,
enableUserSelectHack: true,
offsetParent: null,
handle: null,
grid: null,
transform: null,
onStart: function onStart() {},
onDrag: function onDrag() {},
onStop: function onStop() {},
onMouseDown: function onMouseDown() {}
};
/*:: import type {DraggableEventHandler} from './utils/types';*/
/*:: import type {Element as ReactElement} from 'react';*/
/*:: type DraggableState = {
dragging: boolean,
dragged: boolean,
x: number, y: number,
slackX: number, slackY: number,
isElementSVG: boolean
};*/
//
// Define <Draggable>
//
/*:: export type DraggableProps = {
...$Exact<DraggableCoreProps>,
axis: 'both' | 'x' | 'y' | 'none',
bounds: DraggableBounds | string | false,
defaultClassName: string,
defaultClassNameDragging: string,
defaultClassNameDragged: string,
defaultPosition: ControlPosition,
positionOffset: PositionOffsetControlPosition,
position: ControlPosition,
scale: number
};*/
var Draggable = function (_React$Component) {
inherits(Draggable, _React$Component);
function Draggable(props /*: DraggableProps*/) {
classCallCheck(this, Draggable);
var _this = possibleConstructorReturn(this, (Draggable.__proto__ || Object.getPrototypeOf(Draggable)).call(this, props));
_this.onDragStart = function (e, coreData) {
// Short-circuit if user's callback killed it.
var shouldStart = _this.props.onStart(e, createDraggableData(_this, coreData));
// Kills start event on core as well, so move handlers are never bound.
if (shouldStart === false) return false;
_this.setState({ dragging: true, dragged: true });
};
_this.onDrag = function (e, coreData) {
if (!_this.state.dragging) return false;
var uiData = createDraggableData(_this, coreData);
var newState /*: $Shape<DraggableState>*/ = {
x: uiData.x,
y: uiData.y
};
// Keep within bounds.
if (_this.props.bounds) {
// Save original x and y.
var _x = newState.x,
_y = newState.y;
// Add slack to the values used to calculate bound position. This will ensure that if
// we start removing slack, the element won't react to it right away until it's been
// completely removed.
newState.x += _this.state.slackX;
newState.y += _this.state.slackY;
// Get bound position. This will ceil/floor the x and y within the boundaries.
var _getBoundPosition = getBoundPosition(_this, newState.x, newState.y),
_getBoundPosition2 = slicedToArray(_getBoundPosition, 2),
newStateX = _getBoundPosition2[0],
newStateY = _getBoundPosition2[1];
newState.x = newStateX;
newState.y = newStateY;
// Recalculate slack by noting how much was shaved by the boundPosition handler.
newState.slackX = _this.state.slackX + (_x - newState.x);
newState.slackY = _this.state.slackY + (_y - newState.y);
// Update the event we fire to reflect what really happened after bounds took effect.
uiData.x = newState.x;
uiData.y = newState.y;
uiData.deltaX = newState.x - _this.state.x;
uiData.deltaY = newState.y - _this.state.y;
}
// Short-circuit if user's callback killed it.
var shouldUpdate = _this.props.onDrag(e, uiData);
if (shouldUpdate === false) return false;
_this.setState(newState);
};
_this.onDragStop = function (e, coreData) {
if (!_this.state.dragging) return false;
// Short-circuit if user's callback killed it.
var shouldStop = _this.props.onStop(e, createDraggableData(_this, coreData));
if (shouldStop === false) return false;
var newState /*: $Shape<DraggableState>*/ = {
dragging: false,
slackX: 0,
slackY: 0
};
// If this is a controlled component, the result of this operation will be to
// revert back to the old position. We expect a handler on `onDragStop`, at the least.
var controlled = Boolean(_this.props.position);
if (controlled) {
var _this$props$position = _this.props.position,
_x2 = _this$props$position.x,
_y2 = _this$props$position.y;
newState.x = _x2;
newState.y = _y2;
}
_this.setState(newState);
};
_this.state = {
// Whether or not we are currently dragging.
dragging: false,
// Whether or not we have been dragged before.
dragged: false,
// Current transform x and y.
x: props.position ? props.position.x : props.defaultPosition.x,
y: props.position ? props.position.y : props.defaultPosition.y,
// Used for compensating for out-of-bounds drags
slackX: 0, slackY: 0,
// Can only determine if SVG after mounting
isElementSVG: false
};
return _this;
}
createClass(Draggable, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.props.position && !(this.props.onDrag || this.props.onStop)) {
// eslint-disable-next-line
console.warn('A `position` was applied to this <Draggable>, without drag handlers. This will make this ' + 'component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the ' + '`position` of this element.');
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
// Check to see if the element passed is an instanceof SVGElement
if (typeof window.SVGElement !== 'undefined' && ReactDOM.findDOMNode(this) instanceof window.SVGElement) {
this.setState({ isElementSVG: true });
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps /*: Object*/) {
// Set x/y if position has changed
if (nextProps.position && (!this.props.position || nextProps.position.x !== this.props.position.x || nextProps.position.y !== this.props.position.y)) {
this.setState({ x: nextProps.position.x, y: nextProps.position.y });
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.setState({ dragging: false }); // prevents invariant if unmounted while dragging
}
}, {
key: 'render',
value: function render() /*: ReactElement<any>*/ {
var _classNames;
var style = {},
svgTransform = null;
// If this is controlled, we don't want to move it - unless it's dragging.
var controlled = Boolean(this.props.position);
var draggable = !controlled || this.state.dragging;
var position = this.props.position || this.props.defaultPosition;
var transformOpts = {
// Set left if horizontal drag is enabled
x: canDragX(this) && draggable ? this.state.x : position.x,
// Set top if vertical drag is enabled
y: canDragY(this) && draggable ? this.state.y : position.y
};
// If this element was SVG, we use the `transform` attribute.
if (this.state.isElementSVG) {
svgTransform = createSVGTransform(transformOpts, this.props.positionOffset);
} else {
// Add a CSS transform to move the element around. This allows us to move the element around
// without worrying about whether or not it is relatively or absolutely positioned.
// If the item you are dragging already has a transform set, wrap it in a <span> so <Draggable>
// has a clean slate.
style = createCSSTransform(transformOpts, this.props.positionOffset);
}
var _props = this.props,
defaultClassName = _props.defaultClassName,
defaultClassNameDragging = _props.defaultClassNameDragging,
defaultClassNameDragged = _props.defaultClassNameDragged;
var children = React.Children.only(this.props.children);
// Mark with class while dragging
var className = classnames(children.props.className || '', defaultClassName, (_classNames = {}, defineProperty(_classNames, defaultClassNameDragging, this.state.dragging), defineProperty(_classNames, defaultClassNameDragged, this.state.dragged), _classNames));
// Reuse the child provided
// This makes it flexible to use whatever element is wanted (div, ul, etc)
return React.createElement(
DraggableCore,
_extends({}, this.props, { onStart: this.onDragStart, onDrag: this.onDrag, onStop: this.onDragStop }),
React.cloneElement(children, {
className: className,
style: _extends({}, children.props.style, style),
transform: svgTransform
})
);
}
}]);
return Draggable;
}(React.Component);
Draggable.displayName = 'Draggable';
Draggable.propTypes = _extends({}, DraggableCore.propTypes, {
/**
* `axis` determines which axis the draggable can move.
*
* Note that all callbacks will still return data as normal. This only
* controls flushing to the DOM.
*
* 'both' allows movement horizontally and vertically.
* 'x' limits movement to horizontal axis.
* 'y' limits movement to vertical axis.
* 'none' limits all movement.
*
* Defaults to 'both'.
*/
axis: propTypes.oneOf(['both', 'x', 'y', 'none']),
/**
* `bounds` determines the range of movement available to the element.
* Available values are:
*
* 'parent' restricts movement within the Draggable's parent node.
*
* Alternatively, pass an object with the following properties, all of which are optional:
*
* {left: LEFT_BOUND, right: RIGHT_BOUND, bottom: BOTTOM_BOUND, top: TOP_BOUND}
*
* All values are in px.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable bounds={{right: 300, bottom: 300}}>
* <div>Content</div>
* </Draggable>
* );
* }
* });
* ```
*/
bounds: propTypes.oneOfType([propTypes.shape({
left: propTypes.number,
right: propTypes.number,
top: propTypes.number,
bottom: propTypes.number
}), propTypes.string, propTypes.oneOf([false])]),
defaultClassName: propTypes.string,
defaultClassNameDragging: propTypes.string,
defaultClassNameDragged: propTypes.string,
/**
* `defaultPosition` specifies the x and y that the dragged item should start at
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable defaultPosition={{x: 25, y: 25}}>
* <div>I start with transformX: 25px and transformY: 25px;</div>
* </Draggable>
* );
* }
* });
* ```
*/
defaultPosition: propTypes.shape({
x: propTypes.number,
y: propTypes.number
}),
positionOffset: propTypes.shape({
x: propTypes.oneOfType([propTypes.number, propTypes.string]),
y: propTypes.oneOfType([propTypes.number, propTypes.string])
}),
/**
* `position`, if present, defines the current position of the element.
*
* This is similar to how form elements in React work - if no `position` is supplied, the component
* is uncontrolled.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable position={{x: 25, y: 25}}>
* <div>I start with transformX: 25px and transformY: 25px;</div>
* </Draggable>
* );
* }
* });
* ```
*/
position: propTypes.shape({
x: propTypes.number,
y: propTypes.number
}),
/**
* These properties should be defined on the child, not here.
*/
className: dontSetMe,
style: dontSetMe,
transform: dontSetMe
});
Draggable.defaultProps = _extends({}, DraggableCore.defaultProps, {
axis: 'both',
bounds: false,
defaultClassName: 'react-draggable',
defaultClassNameDragging: 'react-draggable-dragging',
defaultClassNameDragged: 'react-draggable-dragged',
defaultPosition: { x: 0, y: 0 },
position: null,
scale: 1
});
// Previous versions of this lib exported <Draggable> as the root export. As to not break
// them, or TypeScript, we export *both* as the root and as 'default'.
// See https://github.com/mzabriskie/react-draggable/pull/254
// and https://github.com/mzabriskie/react-draggable/issues/266
Draggable.default = Draggable;
Draggable.DraggableCore = DraggableCore;
return Draggable;
})));
//# sourceMappingURL=react-draggable.js.map
/***/ }),
/* 255 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, module) {/**
* Lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright JS Foundation and other contributors <https://js.foundation/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice,
symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeKeys = overArg(Object.keys, Object);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = isEqual;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(205)(module)))
/***/ }),
/* 256 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _reactBeautifulDnd = __webpack_require__(156);
var _util = __webpack_require__(257);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _lodash = __webpack_require__(255);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var reorder = function reorder(list, startIndex, endIndex) {
var result = Array.from(list);
var _result$splice = result.splice(startIndex, 1),
_result$splice2 = _slicedToArray(_result$splice, 1),
removed = _result$splice2[0];
result.splice(endIndex, 0, removed);
return result;
};
var Vertical = function (_Component) {
_inherits(Vertical, _Component);
function Vertical(props) {
_classCallCheck(this, Vertical);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onDragEnd = function (result) {
if (!result.destination) {
return;
}
var items = reorder(_this.state.items, result.source.index, result.destination.index);
_this.setState({
items: items
});
_this.props.onStop(result, items);
};
_this.onDragStart = function (result) {
_this.props.onStart(result, _this.state.items);
};
_this.state = {
items: _this.props.list || []
};
return _this;
}
Vertical.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (!(0, _lodash2["default"])(this.state.items, nextProps.list)) {
this.setState({
items: nextProps.list
});
}
};
Vertical.prototype.render = function render() {
var _this2 = this;
var _props = this.props,
onStart = _props.onStart,
onDrag = _props.onDrag,
onStop = _props.onStop,
onDragUpdate = _props.onDragUpdate,
dropClass = _props.dropClass,
dropOverClass = _props.dropOverClass,
dragClass = _props.dragClass,
dragingClass = _props.dragingClass,
showKey = _props.showKey,
type = _props.type;
return _react2["default"].createElement(
_reactBeautifulDnd.DragDropContext,
{ onDragEnd: this.onDragEnd, onDragStart: this.onDragStart, onDragUpdate: onDragUpdate },
_react2["default"].createElement(
_reactBeautifulDnd.Droppable,
{ droppableId: 'droppable', direction: type },
function (provided, snapshot) {
return _react2["default"].createElement(
'div',
{
ref: provided.innerRef,
className: (0, _classnames2["default"])(_extends({}, (0, _util.getClass)(_this2.props, snapshot.isDraggingOver).drop))
},
_this2.state.items.map(function (item, index) {
return _react2["default"].createElement(
_reactBeautifulDnd.Draggable,
{ key: index, draggableId: index, index: index },
function (provided, snapshot) {
return _react2["default"].createElement(
'div',
_extends({
ref: provided.innerRef
}, provided.draggableProps, provided.dragHandleProps, {
className: (0, _classnames2["default"])(_extends({}, (0, _util.getClass)(_this2.props, snapshot.isDragging).drag)),
style: _extends({}, provided.draggableProps.style)
}),
showKey ? item[showKey] : item
);
}
);
}),
provided.placeholder
);
}
)
);
};
return Vertical;
}(_react.Component);
exports["default"] = Vertical;
module.exports = exports['default'];
/***/ }),
/* 257 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var getClass = exports.getClass = function getClass(props, doing) {
var dropClass = props.dropClass,
dropOverClass = props.dropOverClass,
dragClass = props.dragClass,
dragingClass = props.dragingClass,
type = props.type;
var verticalObj = {
drop: {}, drag: {}
};
verticalObj.drop['u-drop ' + dropClass] = true;
verticalObj.drop['u-droping ' + dropOverClass] = doing;
verticalObj.drag['u-drag ' + dragClass] = true;
verticalObj.drag['u-draging ' + dragingClass] = doing;
var horizontalObj = {
drop: {}, drag: {}
};
horizontalObj.drop['u-drop u-drop-horizontal ' + dropClass] = true;
horizontalObj.drop['u-droping u-droping-horizontal ' + dropOverClass] = doing;
horizontalObj.drag['u-drag u-drag-horizontal ' + dragClass] = true;
horizontalObj.drag['u-draging u-draging-horizontal ' + dragingClass] = doing;
switch (type) {
case 'vertical':
return verticalObj;
break;
case 'horizontal':
return horizontalObj;
break;
case 'betweenVertical':
return verticalObj;
break;
case 'betweenHorizontal':
return horizontalObj;
break;
}
};
/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _reactBeautifulDnd = __webpack_require__(156);
var _util = __webpack_require__(257);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _lodash = __webpack_require__(255);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var reorder = function reorder(list, startIndex, endIndex) {
var result = Array.from(list);
var _result$splice = result.splice(startIndex, 1),
_result$splice2 = _slicedToArray(_result$splice, 1),
removed = _result$splice2[0];
result.splice(endIndex, 0, removed);
return result;
};
/**
* Moves an item from one list to another list.
*/
var move = function move(source, destination, droppableSource, droppableDestination) {
var sourceClone = Array.from(source);
var destClone = Array.from(destination);
var _sourceClone$splice = sourceClone.splice(droppableSource.index, 1),
_sourceClone$splice2 = _slicedToArray(_sourceClone$splice, 1),
removed = _sourceClone$splice2[0];
destClone.splice(droppableDestination.index, 0, removed);
var result = {};
result[droppableSource.droppableId] = sourceClone;
result[droppableDestination.droppableId] = destClone;
return result;
};
var Between = function (_Component) {
_inherits(Between, _Component);
function Between(props) {
_classCallCheck(this, Between);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.id2List = {
droppable: 'items',
droppable2: 'selected'
};
_this.getList = function (id) {
return _this.state[_this.id2List[id]];
};
_this.onDragEnd = function (result) {
console.log(result);
var source = result.source,
destination = result.destination;
// dropped outside the list
if (!destination) {
return;
}
var list = _this.state.items;
var otherList = _this.state.selected;
if (source.droppableId === destination.droppableId) {
var items = reorder(_this.getList(source.droppableId), source.index, destination.index);
var state = { items: items };
list = items;
if (source.droppableId === 'droppable2') {
state = { selected: items };
otherList = items;
list = _this.state.items;
}
_this.setState(state);
} else {
var _result = move(_this.getList(source.droppableId), _this.getList(destination.droppableId), source, destination);
_this.setState({
items: _result.droppable,
selected: _result.droppable2
});
list = _result.droppable;
otherList = _result.droppable2;
}
_this.props.onStop(result, {
list: list,
otherList: otherList
});
};
_this.onDragStart = function (result) {
_this.props.onStart(result, {
list: _this.state.list,
otherList: _this.state.selected
});
};
_this.state = {
items: _this.props.list,
selected: _this.props.otherList
};
return _this;
}
Between.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (!(0, _lodash2["default"])(this.state.items, nextProps.list)) {
this.setState({
items: nextProps.list
});
}
if (!(0, _lodash2["default"])(this.state.selected, nextProps.otherList)) {
this.setState({
selected: nextProps.otherList
});
}
};
Between.prototype.render = function render() {
var _this2 = this;
var _props = this.props,
onStart = _props.onStart,
onDrag = _props.onDrag,
onStop = _props.onStop,
onDragUpdate = _props.onDragUpdate,
dropClass = _props.dropClass,
dropOverClass = _props.dropOverClass,
dragClass = _props.dragClass,
dragingClass = _props.dragingClass,
showKey = _props.showKey,
type = _props.type;
return _react2["default"].createElement(
'div',
{ className: (0, _classnames2["default"])({
'u-drag-between': type == 'betweenVertical',
'u-drag-between u-drag-between-horizontal': type == 'betweenHorizontal'
}) },
_react2["default"].createElement(
_reactBeautifulDnd.DragDropContext,
{ onDragEnd: this.onDragEnd, onDragStart: this.onDragStart, onDragUpdate: onDragUpdate },
_react2["default"].createElement(
_reactBeautifulDnd.Droppable,
{ droppableId: 'droppable', direction: type == 'betweenVertical' ? 'vertical' : 'horizontal' },
function (provided, snapshot) {
return _react2["default"].createElement(
'div',
{
ref: provided.innerRef,
className: (0, _classnames2["default"])(_extends({}, (0, _util.getClass)(_this2.props, snapshot.isDraggingOver).drop)) },
_this2.state.items.map(function (item, index) {
return _react2["default"].createElement(
_reactBeautifulDnd.Draggable,
{
key: '1' + index,
draggableId: '1' + index,
index: index },
function (provided, snapshot) {
return _react2["default"].createElement(
'div',
_extends({
ref: provided.innerRef
}, provided.draggableProps, provided.dragHandleProps, {
className: (0, _classnames2["default"])(_extends({}, (0, _util.getClass)(_this2.props, snapshot.isDragging).drag)),
style: _extends({}, provided.draggableProps.style) }),
showKey ? item[showKey] : item
);
}
);
}),
provided.placeholder
);
}
),
_react2["default"].createElement(
_reactBeautifulDnd.Droppable,
{ droppableId: 'droppable2', direction: type == 'betweenVertical' ? 'vertical' : 'horizontal' },
function (provided, snapshot) {
return _react2["default"].createElement(
'div',
{
ref: provided.innerRef,
className: (0, _classnames2["default"])(_extends({}, (0, _util.getClass)(_this2.props, snapshot.isDraggingOver).drop)) },
_this2.state.selected.map(function (item, index) {
return _react2["default"].createElement(
_reactBeautifulDnd.Draggable,
{
key: '2' + index,
draggableId: '2' + index,
index: index },
function (provided, snapshot) {
return _react2["default"].createElement(
'div',
_extends({
ref: provided.innerRef
}, provided.draggableProps, provided.dragHandleProps, {
className: (0, _classnames2["default"])(_extends({}, (0, _util.getClass)(_this2.props, snapshot.isDragging).drag)),
style: _extends({}, provided.draggableProps.style) }),
showKey ? item[showKey] : item
);
}
);
}),
provided.placeholder
);
}
)
)
);
};
return Between;
}(_react.Component);
exports["default"] = Between;
module.exports = exports['default'];
/***/ }),
/* 259 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var styles = {
base: {
position: 'absolute',
userSelect: 'none',
MsUserSelect: 'none'
},
top: {
width: '100%',
height: '10px',
top: '-5px',
left: '0px',
cursor: 'row-resize'
},
right: {
width: '10px',
height: '100%',
top: '0px',
right: '-5px',
cursor: 'col-resize'
},
bottom: {
width: '100%',
height: '10px',
bottom: '-5px',
left: '0px',
cursor: 'row-resize'
},
left: {
width: '10px',
height: '100%',
top: '0px',
left: '-5px',
cursor: 'col-resize'
},
topRight: {
width: '20px',
height: '20px',
position: 'absolute',
right: '-10px',
top: '-10px',
cursor: 'ne-resize'
},
bottomRight: {
width: '20px',
height: '20px',
position: 'absolute',
right: '-10px',
bottom: '-10px',
cursor: 'se-resize'
},
bottomLeft: {
width: '20px',
height: '20px',
position: 'absolute',
left: '-10px',
bottom: '-10px',
cursor: 'sw-resize'
},
topLeft: {
width: '20px',
height: '20px',
position: 'absolute',
left: '-10px',
top: '-10px',
cursor: 'nw-resize'
}
};
var Resizer = (function (props) {
return React.createElement(
'div',
{
className: props.className,
style: _extends({}, styles.base, styles[props.direction], props.replaceStyles || {}),
onMouseDown: function onMouseDown(e) {
props.onResizeStart(e, props.direction);
},
onTouchStart: function onTouchStart(e) {
props.onResizeStart(e, props.direction);
}
},
props.children
);
});
var userSelectNone = {
userSelect: 'none',
MozUserSelect: 'none',
WebkitUserSelect: 'none',
MsUserSelect: 'none'
};
var userSelectAuto = {
userSelect: 'auto',
MozUserSelect: 'auto',
WebkitUserSelect: 'auto',
MsUserSelect: 'auto'
};
var clamp = function clamp(n, min, max) {
return Math.max(Math.min(n, max), min);
};
var snap = function snap(n, size) {
return Math.round(n / size) * size;
};
var findClosestSnap = function findClosestSnap(n, snapArray) {
return snapArray.reduce(function (prev, curr) {
return Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev;
});
};
var endsWith = function endsWith(str, searchStr) {
return str.substr(str.length - searchStr.length, searchStr.length) === searchStr;
};
var getStringSize = function getStringSize(n) {
if (n.toString() === 'auto') return n.toString();
if (endsWith(n.toString(), 'px')) return n.toString();
if (endsWith(n.toString(), '%')) return n.toString();
if (endsWith(n.toString(), 'vh')) return n.toString();
if (endsWith(n.toString(), 'vw')) return n.toString();
if (endsWith(n.toString(), 'vmax')) return n.toString();
if (endsWith(n.toString(), 'vmin')) return n.toString();
return n + 'px';
};
var definedProps = ['style', 'className', 'grid', 'snap', 'bounds', 'size', 'defaultSize', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'lockAspectRatio', 'lockAspectRatioExtraWidth', 'lockAspectRatioExtraHeight', 'enable', 'handleStyles', 'handleClasses', 'handleWrapperStyle', 'handleWrapperClass', 'children', 'onResizeStart', 'onResize', 'onResizeStop', 'handleComponent', 'scale', 'resizeRatio'];
var baseClassName = '__resizable_base__';
var Resizable = function (_React$Component) {
inherits(Resizable, _React$Component);
function Resizable(props) {
classCallCheck(this, Resizable);
var _this = possibleConstructorReturn(this, (Resizable.__proto__ || Object.getPrototypeOf(Resizable)).call(this, props));
_this.state = {
isResizing: false,
resizeCursor: 'auto',
width: typeof (_this.propsSize && _this.propsSize.width) === 'undefined' ? 'auto' : _this.propsSize && _this.propsSize.width,
height: typeof (_this.propsSize && _this.propsSize.height) === 'undefined' ? 'auto' : _this.propsSize && _this.propsSize.height,
direction: 'right',
original: {
x: 0,
y: 0,
width: 0,
height: 0
}
};
_this.updateExtendsProps(props);
_this.onResizeStart = _this.onResizeStart.bind(_this);
_this.onMouseMove = _this.onMouseMove.bind(_this);
_this.onMouseUp = _this.onMouseUp.bind(_this);
if (typeof window !== 'undefined') {
window.addEventListener('mouseup', _this.onMouseUp);
window.addEventListener('mousemove', _this.onMouseMove);
window.addEventListener('mouseleave', _this.onMouseUp);
window.addEventListener('touchmove', _this.onMouseMove);
window.addEventListener('touchend', _this.onMouseUp);
}
return _this;
}
createClass(Resizable, [{
key: 'updateExtendsProps',
value: function updateExtendsProps(props) {
this.extendsProps = Object.keys(props).reduce(function (acc, key) {
if (definedProps.indexOf(key) !== -1) return acc;
acc[key] = props[key];
return acc;
}, {});
}
}, {
key: 'getParentSize',
value: function getParentSize() {
var base = this.base;
if (!base) return { width: window.innerWidth, height: window.innerHeight };
// INFO: To calculate parent width with flex layout
var wrapChanged = false;
var wrap = this.parentNode.style.flexWrap;
var minWidth = base.style.minWidth;
if (wrap !== 'wrap') {
wrapChanged = true;
this.parentNode.style.flexWrap = 'wrap';
// HACK: Use relative to get parent padding size
}
base.style.position = 'relative';
base.style.minWidth = '100%';
var size = {
width: base.offsetWidth,
height: base.offsetHeight
};
base.style.position = 'absolute';
if (wrapChanged) this.parentNode.style.flexWrap = wrap;
base.style.minWidth = minWidth;
return size;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var size = this.size;
this.setState({
width: this.state.width || size.width,
height: this.state.height || size.height
});
var parent = this.parentNode;
if (!(parent instanceof HTMLElement)) return;
if (this.base) return;
var element = document.createElement('div');
element.style.width = '100%';
element.style.height = '100%';
element.style.position = 'absolute';
element.style.transform = 'scale(0, 0)';
element.style.left = '0';
element.style.flex = '0';
if (element.classList) {
element.classList.add(baseClassName);
} else {
element.className += baseClassName;
}
parent.appendChild(element);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(next) {
this.updateExtendsProps(next);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (typeof window !== 'undefined') {
window.removeEventListener('mouseup', this.onMouseUp);
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener('mouseleave', this.onMouseUp);
window.removeEventListener('touchmove', this.onMouseMove);
window.removeEventListener('touchend', this.onMouseUp);
var parent = this.parentNode;
var base = this.base;
if (!base || !parent) return;
if (!(parent instanceof HTMLElement) || !(base instanceof Node)) return;
parent.removeChild(base);
}
}
}, {
key: 'calculateNewSize',
value: function calculateNewSize(newSize, kind) {
var propsSize = this.propsSize && this.propsSize[kind];
return this.state[kind] === 'auto' && this.state.original[kind] === newSize && (typeof propsSize === 'undefined' || propsSize === 'auto') ? 'auto' : newSize;
}
}, {
key: 'onResizeStart',
value: function onResizeStart(event, direction) {
var clientX = 0;
var clientY = 0;
if (event.nativeEvent instanceof MouseEvent) {
clientX = event.nativeEvent.clientX;
clientY = event.nativeEvent.clientY;
// When user click with right button the resize is stuck in resizing mode
// until users clicks again, dont continue if right click is used.
// HACK: MouseEvent does not have `which` from flow-bin v0.68.
if (event.nativeEvent.which === 3) {
return;
}
} else if (event.nativeEvent instanceof TouchEvent) {
clientX = event.nativeEvent.touches[0].clientX;
clientY = event.nativeEvent.touches[0].clientY;
}
if (this.props.onResizeStart) {
this.props.onResizeStart(event, direction, this.resizable);
}
// Fix #168
if (this.props.size) {
if (typeof this.props.size.height !== 'undefined' && this.props.size.height !== this.state.height) {
this.setState({ height: this.props.size.height });
}
if (typeof this.props.size.width !== 'undefined' && this.props.size.width !== this.state.width) {
this.setState({ width: this.props.size.width });
}
}
this.setState({
original: {
x: clientX,
y: clientY,
width: this.size.width,
height: this.size.height
},
isResizing: true,
resizeCursor: window.getComputedStyle(event.target).cursor,
direction: direction
});
}
}, {
key: 'onMouseMove',
value: function onMouseMove(event) {
if (!this.state.isResizing) return;
var clientX = event instanceof MouseEvent ? event.clientX : event.touches[0].clientX;
var clientY = event instanceof MouseEvent ? event.clientY : event.touches[0].clientY;
var _state = this.state,
direction = _state.direction,
original = _state.original,
width = _state.width,
height = _state.height;
var _props = this.props,
lockAspectRatio = _props.lockAspectRatio,
lockAspectRatioExtraHeight = _props.lockAspectRatioExtraHeight,
lockAspectRatioExtraWidth = _props.lockAspectRatioExtraWidth;
var scale = this.props.scale || 1;
var _props2 = this.props,
maxWidth = _props2.maxWidth,
maxHeight = _props2.maxHeight,
minWidth = _props2.minWidth,
minHeight = _props2.minHeight;
var resizeRatio = this.props.resizeRatio || 1;
// TODO: refactor
var parentSize = this.getParentSize();
if (maxWidth && typeof maxWidth === 'string' && endsWith(maxWidth, '%')) {
var _ratio = Number(maxWidth.replace('%', '')) / 100;
maxWidth = parentSize.width * _ratio;
}
if (maxHeight && typeof maxHeight === 'string' && endsWith(maxHeight, '%')) {
var _ratio2 = Number(maxHeight.replace('%', '')) / 100;
maxHeight = parentSize.height * _ratio2;
}
if (minWidth && typeof minWidth === 'string' && endsWith(minWidth, '%')) {
var _ratio3 = Number(minWidth.replace('%', '')) / 100;
minWidth = parentSize.width * _ratio3;
}
if (minHeight && typeof minHeight === 'string' && endsWith(minHeight, '%')) {
var _ratio4 = Number(minHeight.replace('%', '')) / 100;
minHeight = parentSize.height * _ratio4;
}
maxWidth = typeof maxWidth === 'undefined' ? undefined : Number(maxWidth);
maxHeight = typeof maxHeight === 'undefined' ? undefined : Number(maxHeight);
minWidth = typeof minWidth === 'undefined' ? undefined : Number(minWidth);
minHeight = typeof minHeight === 'undefined' ? undefined : Number(minHeight);
var ratio = typeof lockAspectRatio === 'number' ? lockAspectRatio : original.width / original.height;
var newWidth = original.width;
var newHeight = original.height;
if (/right/i.test(direction)) {
newWidth = original.width + (clientX - original.x) * resizeRatio / scale;
if (lockAspectRatio) newHeight = (newWidth - lockAspectRatioExtraWidth) / ratio + lockAspectRatioExtraHeight;
}
if (/left/i.test(direction)) {
newWidth = original.width - (clientX - original.x) * resizeRatio / scale;
if (lockAspectRatio) newHeight = (newWidth - lockAspectRatioExtraWidth) / ratio + lockAspectRatioExtraHeight;
}
if (/bottom/i.test(direction)) {
newHeight = original.height + (clientY - original.y) * resizeRatio / scale;
if (lockAspectRatio) newWidth = (newHeight - lockAspectRatioExtraHeight) * ratio + lockAspectRatioExtraWidth;
}
if (/top/i.test(direction)) {
newHeight = original.height - (clientY - original.y) * resizeRatio / scale;
if (lockAspectRatio) newWidth = (newHeight - lockAspectRatioExtraHeight) * ratio + lockAspectRatioExtraWidth;
}
if (this.props.bounds === 'parent') {
var parent = this.parentNode;
if (parent instanceof HTMLElement) {
var parentRect = parent.getBoundingClientRect();
var parentLeft = parentRect.left;
var parentTop = parentRect.top;
var _resizable$getBoundin = this.resizable.getBoundingClientRect(),
_left = _resizable$getBoundin.left,
_top = _resizable$getBoundin.top;
var boundWidth = parent.offsetWidth + (parentLeft - _left);
var boundHeight = parent.offsetHeight + (parentTop - _top);
maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth;
maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight;
}
} else if (this.props.bounds === 'window') {
if (typeof window !== 'undefined') {
var _resizable$getBoundin2 = this.resizable.getBoundingClientRect(),
_left2 = _resizable$getBoundin2.left,
_top2 = _resizable$getBoundin2.top;
var _boundWidth = window.innerWidth - _left2;
var _boundHeight = window.innerHeight - _top2;
maxWidth = maxWidth && maxWidth < _boundWidth ? maxWidth : _boundWidth;
maxHeight = maxHeight && maxHeight < _boundHeight ? maxHeight : _boundHeight;
}
} else if (this.props.bounds instanceof HTMLElement) {
var targetRect = this.props.bounds.getBoundingClientRect();
var targetLeft = targetRect.left;
var targetTop = targetRect.top;
var _resizable$getBoundin3 = this.resizable.getBoundingClientRect(),
_left3 = _resizable$getBoundin3.left,
_top3 = _resizable$getBoundin3.top;
if (!(this.props.bounds instanceof HTMLElement)) return;
var _boundWidth2 = this.props.bounds.offsetWidth + (targetLeft - _left3);
var _boundHeight2 = this.props.bounds.offsetHeight + (targetTop - _top3);
maxWidth = maxWidth && maxWidth < _boundWidth2 ? maxWidth : _boundWidth2;
maxHeight = maxHeight && maxHeight < _boundHeight2 ? maxHeight : _boundHeight2;
}
var computedMinWidth = typeof minWidth === 'undefined' ? 10 : minWidth;
var computedMaxWidth = typeof maxWidth === 'undefined' || maxWidth < 0 ? newWidth : maxWidth;
var computedMinHeight = typeof minHeight === 'undefined' ? 10 : minHeight;
var computedMaxHeight = typeof maxHeight === 'undefined' || maxHeight < 0 ? newHeight : maxHeight;
if (lockAspectRatio) {
var extraMinWidth = (computedMinHeight - lockAspectRatioExtraHeight) * ratio + lockAspectRatioExtraWidth;
var extraMaxWidth = (computedMaxHeight - lockAspectRatioExtraHeight) * ratio + lockAspectRatioExtraWidth;
var extraMinHeight = (computedMinWidth - lockAspectRatioExtraWidth) / ratio + lockAspectRatioExtraHeight;
var extraMaxHeight = (computedMaxWidth - lockAspectRatioExtraWidth) / ratio + lockAspectRatioExtraHeight;
var lockedMinWidth = Math.max(computedMinWidth, extraMinWidth);
var lockedMaxWidth = Math.min(computedMaxWidth, extraMaxWidth);
var lockedMinHeight = Math.max(computedMinHeight, extraMinHeight);
var lockedMaxHeight = Math.min(computedMaxHeight, extraMaxHeight);
newWidth = clamp(newWidth, lockedMinWidth, lockedMaxWidth);
newHeight = clamp(newHeight, lockedMinHeight, lockedMaxHeight);
} else {
newWidth = clamp(newWidth, computedMinWidth, computedMaxWidth);
newHeight = clamp(newHeight, computedMinHeight, computedMaxHeight);
}
if (this.props.grid) {
newWidth = snap(newWidth, this.props.grid[0]);
}
if (this.props.grid) {
newHeight = snap(newHeight, this.props.grid[1]);
}
if (this.props.snap && this.props.snap.x) {
newWidth = findClosestSnap(newWidth, this.props.snap.x);
}
if (this.props.snap && this.props.snap.y) {
newHeight = findClosestSnap(newHeight, this.props.snap.y);
}
var delta = {
width: newWidth - original.width,
height: newHeight - original.height
};
if (width && typeof width === 'string' && endsWith(width, '%')) {
var percent = newWidth / parentSize.width * 100;
newWidth = percent + '%';
}
if (height && typeof height === 'string' && endsWith(height, '%')) {
var _percent = newHeight / parentSize.height * 100;
newHeight = _percent + '%';
}
this.setState({
width: this.calculateNewSize(newWidth, 'width'),
height: this.calculateNewSize(newHeight, 'height')
});
if (this.props.onResize) {
this.props.onResize(event, direction, this.resizable, delta);
}
}
}, {
key: 'onMouseUp',
value: function onMouseUp(event) {
var _state2 = this.state,
isResizing = _state2.isResizing,
direction = _state2.direction,
original = _state2.original;
if (!isResizing) return;
var delta = {
width: this.size.width - original.width,
height: this.size.height - original.height
};
if (this.props.onResizeStop) {
this.props.onResizeStop(event, direction, this.resizable, delta);
}
if (this.props.size) {
this.setState(this.props.size);
}
this.setState({ isResizing: false, resizeCursor: 'auto' });
}
}, {
key: 'updateSize',
value: function updateSize(size) {
this.setState({ width: size.width, height: size.height });
}
}, {
key: 'renderResizer',
value: function renderResizer() {
var _this2 = this;
var _props3 = this.props,
enable = _props3.enable,
handleStyles = _props3.handleStyles,
handleClasses = _props3.handleClasses,
handleWrapperStyle = _props3.handleWrapperStyle,
handleWrapperClass = _props3.handleWrapperClass,
handleComponent = _props3.handleComponent;
if (!enable) return null;
var resizers = Object.keys(enable).map(function (dir) {
if (enable[dir] !== false) {
return React.createElement(
Resizer,
{
key: dir,
direction: dir,
onResizeStart: _this2.onResizeStart,
replaceStyles: handleStyles && handleStyles[dir],
className: handleClasses && handleClasses[dir]
},
handleComponent && handleComponent[dir] ? React.createElement(handleComponent[dir]) : null
);
}
return null;
});
// #93 Wrap the resize box in span (will not break 100% width/height)
return React.createElement(
'span',
{ className: handleWrapperClass, style: handleWrapperStyle },
resizers
);
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var userSelect = this.state.isResizing ? userSelectNone : userSelectAuto;
return React.createElement(
'div',
_extends({
ref: function ref(c) {
if (c) {
_this3.resizable = c;
}
},
style: _extends({
position: 'relative'
}, userSelect, this.props.style, this.sizeStyle, {
maxWidth: this.props.maxWidth,
maxHeight: this.props.maxHeight,
minWidth: this.props.minWidth,
minHeight: this.props.minHeight,
boxSizing: 'border-box'
}),
className: this.props.className
}, this.extendsProps),
this.state.isResizing && React.createElement('div', {
style: {
height: '100%',
width: '100%',
backgroundColor: 'rgba(0,0,0,0)',
cursor: '' + (this.state.resizeCursor || 'auto'),
opacity: '0',
position: 'fixed',
zIndex: '9999',
top: '0',
left: '0',
bottom: '0',
right: '0'
}
}),
this.props.children,
this.renderResizer()
);
}
}, {
key: 'parentNode',
get: function get$$1() {
return this.resizable.parentNode;
}
}, {
key: 'propsSize',
get: function get$$1() {
return this.props.size || this.props.defaultSize;
}
}, {
key: 'base',
get: function get$$1() {
var parent = this.parentNode;
if (!parent) return undefined;
var children = [].slice.call(parent.children);
for (var i = 0; i < children.length; i += 1) {
var n = children[i];
if (n instanceof HTMLElement) {
if (n.classList.contains(baseClassName)) {
return n;
}
}
}
return undefined;
}
}, {
key: 'size',
get: function get$$1() {
var width = 0;
var height = 0;
if (typeof window !== 'undefined') {
var orgWidth = this.resizable.offsetWidth;
var orgHeight = this.resizable.offsetHeight;
// HACK: Set position `relative` to get parent size.
// This is because when re-resizable set `absolute`, I can not get base width correctly.
var orgPosition = this.resizable.style.position;
if (orgPosition !== 'relative') {
this.resizable.style.position = 'relative';
}
// INFO: Use original width or height if set auto.
width = this.resizable.style.width !== 'auto' ? this.resizable.offsetWidth : orgWidth;
height = this.resizable.style.height !== 'auto' ? this.resizable.offsetHeight : orgHeight;
// Restore original position
this.resizable.style.position = orgPosition;
}
return { width: width, height: height };
}
}, {
key: 'sizeStyle',
get: function get$$1() {
var _this4 = this;
var size = this.props.size;
var getSize = function getSize(key) {
if (typeof _this4.state[key] === 'undefined' || _this4.state[key] === 'auto') return 'auto';
if (_this4.propsSize && _this4.propsSize[key] && endsWith(_this4.propsSize[key].toString(), '%')) {
if (endsWith(_this4.state[key].toString(), '%')) return _this4.state[key].toString();
var parentSize = _this4.getParentSize();
var value = Number(_this4.state[key].toString().replace('px', ''));
var percent = value / parentSize[key] * 100;
return percent + '%';
}
return getStringSize(_this4.state[key]);
};
var width = size && typeof size.width !== 'undefined' && !this.state.isResizing ? getStringSize(size.width) : getSize('width');
var height = size && typeof size.height !== 'undefined' && !this.state.isResizing ? getStringSize(size.height) : getSize('height');
return { width: width, height: height };
}
}]);
return Resizable;
}(React.Component);
Resizable.defaultProps = {
onResizeStart: function onResizeStart() {},
onResize: function onResize() {},
onResizeStop: function onResizeStop() {},
enable: {
top: true,
right: true,
bottom: true,
left: true,
topRight: true,
bottomRight: true,
bottomLeft: true,
topLeft: true
},
style: {},
grid: [1, 1],
lockAspectRatio: false,
lockAspectRatioExtraWidth: 0,
lockAspectRatioExtraHeight: 0,
scale: 1,
resizeRatio: 1
};
module.exports = Resizable;
/***/ }),
/* 260 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
componentClass: _tinperBeeCore.elementType
};
var defaultProps = {
componentClass: 'div',
clsPrefix: 'u-modal-footer'
};
var ModalFooter = function (_React$Component) {
_inherits(ModalFooter, _React$Component);
function ModalFooter() {
_classCallCheck(this, ModalFooter);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalFooter.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
clsPrefix = _props.clsPrefix,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'clsPrefix', 'className']);
var classes = {};
classes['' + clsPrefix] = true;
return _react2["default"].createElement(Component, _extends({}, props, {
className: (0, _classnames2["default"])(className, classes)
}));
};
return ModalFooter;
}(_react2["default"].Component);
ModalFooter.propTypes = propTypes;
ModalFooter.defaultProps = defaultProps;
exports["default"] = ModalFooter;
module.exports = exports['default'];
/***/ }),
/* 261 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
/**
* 是否显示关闭按钮
*/
closeButton: _propTypes2["default"].bool,
/**
* 关闭时的钩子函数
*/
onHide: _propTypes2["default"].func
};
var defaultProps = {
'aria-label': 'Close',
closeButton: false,
clsPrefix: 'u-modal-header'
};
var contextTypes = {
$u_modal: _propTypes2["default"].shape({
onHide: _propTypes2["default"].func
})
};
var ModalHeader = function (_React$Component) {
_inherits(ModalHeader, _React$Component);
function ModalHeader() {
_classCallCheck(this, ModalHeader);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalHeader.prototype.render = function render() {
var _props = this.props,
label = _props['aria-label'],
closeButton = _props.closeButton,
onHide = _props.onHide,
className = _props.className,
clsPrefix = _props.clsPrefix,
children = _props.children,
props = _objectWithoutProperties(_props, ['aria-label', 'closeButton', 'onHide', 'className', 'clsPrefix', 'children']);
var modal = this.context.$u_modal;
var classes = {};
classes['' + clsPrefix] = true;
classes['dnd-handle'] = true;
return _react2["default"].createElement(
'div',
_extends({}, props, {
className: (0, _classnames2["default"])(className, classes)
}),
closeButton && _react2["default"].createElement(
'button',
{
type: 'button',
className: 'u-close dnd-cancel',
'aria-label': label,
onClick: (0, _tinperBeeCore.createChainedFunction)(modal.onHide, onHide)
},
_react2["default"].createElement(
'span',
{ 'aria-hidden': 'true' },
_react2["default"].createElement('i', { className: 'uf uf-close' })
)
),
children
);
};
return ModalHeader;
}(_react2["default"].Component);
ModalHeader.propTypes = propTypes;
ModalHeader.defaultProps = defaultProps;
ModalHeader.contextTypes = contextTypes;
exports["default"] = ModalHeader;
module.exports = exports['default'];
/***/ }),
/* 262 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
componentClass: _tinperBeeCore.elementType
};
var defaultProps = {
componentClass: 'h4',
clsPrefix: 'u-modal-title'
};
var ModalTitle = function (_React$Component) {
_inherits(ModalTitle, _React$Component);
function ModalTitle() {
_classCallCheck(this, ModalTitle);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalTitle.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
clsPrefix = _props.clsPrefix,
props = _objectWithoutProperties(_props, ['componentClass', 'className', 'clsPrefix']);
var classes = {};
classes['' + clsPrefix] = true;
classes['clearfix'] = true;
return _react2["default"].createElement(Component, _extends({}, props, {
className: (0, _classnames2["default"])(className, classes)
}));
};
return ModalTitle;
}(_react2["default"].Component);
ModalTitle.propTypes = propTypes;
ModalTitle.defaultProps = defaultProps;
exports["default"] = ModalTitle;
module.exports = exports['default'];
/***/ }),
/* 263 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports["default"] = confirm;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _Modal = __webpack_require__(135);
var _Modal2 = _interopRequireDefault(_Modal);
var _beeButton = __webpack_require__(264);
var _beeButton2 = _interopRequireDefault(_beeButton);
var _beeIcon = __webpack_require__(79);
var _beeIcon2 = _interopRequireDefault(_beeIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var IS_REACT_16 = !!_reactDom2["default"].createPortal;
var ConfirmDialog = function ConfirmDialog(props) {
var onCancel = props.onCancel,
onOk = props.onOk,
close = props.close,
onHide = props.onHide,
show = props.show,
keyboard = props.keyboard,
centered = props.centered,
getContainer = props.getContainer,
maskStyle = props.maskStyle,
okButtonProps = props.okButtonProps,
cancelButtonProps = props.cancelButtonProps,
_props$iconType = props.iconType,
iconType = _props$iconType === undefined ? 'uf-qm-c' : _props$iconType;
// 支持传入{ icon: null }来隐藏`Modal.confirm`默认的Icon
var icon = props.icon === undefined ? iconType : props.icon;
var okType = props.okType || 'primary';
var prefixCls = props.prefixCls || 'u-modal';
var contentPrefixCls = prefixCls + '-confirm';
// 默认为 true保持向下兼容
var okCancel = 'okCancel' in props ? props.okCancel : true;
var width = props.width || 400;
var style = props.style || {};
var backdrop = props.backdrop === undefined ? true : props.backdrop;
// 默认为 false保持旧版默认行为
var maskClosable = props.maskClosable === undefined ? false : props.maskClosable;
// const runtimeLocale = getConfirmLocale();
var okText = props.okText || (okCancel ? "确定" : "知道了");
var cancelText = props.cancelText || "取消";
var autoFocusButton = props.autoFocusButton === null ? false : props.autoFocusButton || 'ok';
var transitionName = props.transitionName || 'zoom';
var maskTransitionName = props.maskTransitionName || 'fade';
var classString = (0, _classnames2["default"])(contentPrefixCls, contentPrefixCls + '-' + props.type, props.className);
var cancelButton = okCancel && _react2["default"].createElement(
_beeButton2["default"],
{
onClick: function onClick() {
close();onCancel ? onCancel() : function () {
return;
};
},
colors: 'secondary',
style: { marginRight: 8 }
},
cancelText
);
var iconNode = typeof icon === 'string' ? _react2["default"].createElement(_beeIcon2["default"], { type: icon }) : icon;
return _react2["default"].createElement(
_Modal2["default"],
{
width: width,
className: classString,
show: show,
onHide: onHide,
backdrop: backdrop },
_react2["default"].createElement(
_Modal2["default"].Header,
null,
_react2["default"].createElement(
_Modal2["default"].Title,
null,
iconNode,
_react2["default"].createElement(
'span',
{ className: contentPrefixCls + '-title' },
props.title
)
)
),
_react2["default"].createElement(
_Modal2["default"].Body,
null,
_react2["default"].createElement(
'div',
{ className: contentPrefixCls + '-content' },
props.content
)
),
_react2["default"].createElement(
_Modal2["default"].Footer,
null,
cancelButton,
_react2["default"].createElement(
_beeButton2["default"],
{
onClick: function onClick() {
close();onOk ? onOk() : function () {
return;
};
},
colors: okType
},
okText
)
)
);
};
function confirm(config) {
var div = document.createElement('div');
document.body.appendChild(div);
var currentConfig = _extends({}, config, { close: close, show: true });
function close() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
currentConfig = _extends({}, currentConfig, {
show: false,
onHide: destroy.bind.apply(destroy, [this].concat(args))
});
if (IS_REACT_16) {
render(currentConfig);
} else {
destroy.apply(undefined, args);
}
}
function update(newConfig) {
currentConfig = _extends({}, currentConfig, newConfig);
render(currentConfig);
}
function destroy() {
var unmountResult = _reactDom2["default"].unmountComponentAtNode(div);
if (unmountResult && div.parentNode) {
div.parentNode.removeChild(div);
}
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var triggerCancel = args.some(function (param) {
return param && param.triggerCancel;
});
if (config.onCancel && triggerCancel) {
config.onCancel.apply(config, args);
}
for (var i = 0; i < _Modal.destroyFns.length; i++) {
var fn = _Modal.destroyFns[i];
if (fn === close) {
_Modal.destroyFns.splice(i, 1);
break;
}
}
}
function render(props) {
_reactDom2["default"].render(_react2["default"].createElement(ConfirmDialog, props), div);
}
render(currentConfig);
_Modal.destroyFns.push(close);
return {
destroy: close,
update: update
};
}
module.exports = exports['default'];
/***/ }),
/* 264 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Button = __webpack_require__(265);
var _Button2 = _interopRequireDefault(_Button);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _Button2["default"];
module.exports = exports['default'];
/***/ }),
/* 265 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
/**
* @title 尺寸
*/
size: _propTypes2["default"].oneOf(['sm', 'md', 'xg', 'lg']),
/**
* @title 样式
*/
style: _propTypes2["default"].object,
/**
* @title 形状
*/
shape: _propTypes2["default"].oneOf(['block', 'round', 'border', 'squared', 'floating', 'pillRight', 'pillLeft', 'icon']),
bordered: _propTypes2["default"].bool,
/**
* @title 类型
*/
colors: _propTypes2["default"].oneOf(['primary', 'secondary', 'accent', 'success', 'info', 'warning', 'danger', 'dark', 'light', 'default']),
/**
* @title 是否禁用
* @veIgnore
*/
disabled: _propTypes2["default"].bool,
/**
* @title 类名
* @veIgnore
*/
className: _propTypes2["default"].string,
/**
* @title <button> 的 type
* @veIgnore
*/
htmlType: _propTypes2["default"].oneOf(['submit', 'button', 'reset']),
isSubmit: _propTypes2["default"].bool //是否作为form的提交按钮
};
var defaultProps = {
disabled: false,
htmlType: 'button',
clsPrefix: 'u-button',
bordered: false,
isSubmit: false
};
var sizeMap = {
sm: 'sm',
md: 'md',
xg: 'xg',
lg: 'lg'
},
colorsMap = {
primary: 'primary',
secondary: 'secondary',
accent: 'accent',
success: 'success',
info: 'info',
warning: 'warning',
danger: 'danger',
dark: 'dark',
light: 'light'
},
shapeMap = {
block: 'block',
round: 'round',
border: 'border',
squared: 'squared',
floating: 'floating',
pillRight: 'pill-right',
pillLeft: 'pill-left',
icon: 'icon'
};
var Button = function (_Component) {
_inherits(Button, _Component);
function Button(props) {
_classCallCheck(this, Button);
return _possibleConstructorReturn(this, _Component.call(this, props));
}
Button.prototype.render = function render() {
var _props = this.props,
colors = _props.colors,
shape = _props.shape,
disabled = _props.disabled,
className = _props.className,
size = _props.size,
bordered = _props.bordered,
children = _props.children,
htmlType = _props.htmlType,
clsPrefix = _props.clsPrefix,
isSubmit = _props.isSubmit,
others = _objectWithoutProperties(_props, ['colors', 'shape', 'disabled', 'className', 'size', 'bordered', 'children', 'htmlType', 'clsPrefix', 'isSubmit']);
var clsObj = {};
if (className) {
clsObj[className] = true;
}
if (sizeMap[size]) {
clsObj[clsPrefix + '-' + sizeMap[size]] = true;
}
if (shapeMap[shape]) {
clsObj[clsPrefix + '-' + shapeMap[shape]] = true;
}
if (colorsMap[colors]) {
clsObj[clsPrefix + '-' + colorsMap[colors]] = true;
}
if (bordered) {
clsObj[clsPrefix + '-border'] = bordered;
}
var classes = (0, _classnames2["default"])(clsPrefix, clsObj);
return _react2["default"].createElement(
'button',
_extends({
type: htmlType,
className: classes,
disabled: disabled
}, others),
this.props.children
);
};
return Button;
}(_react.Component);
Button.propTypes = propTypes;
Button.defaultProps = defaultProps;
exports["default"] = Button;
module.exports = exports['default'];
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _FormControl = __webpack_require__(267);
var _FormControl2 = _interopRequireDefault(_FormControl);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports["default"] = _FormControl2["default"];
module.exports = exports['default'];
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _beeIcon = __webpack_require__(79);
var _beeIcon2 = _interopRequireDefault(_beeIcon);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _rcTextarea = __webpack_require__(268);
var _rcTextarea2 = _interopRequireDefault(_rcTextarea);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var propTypes = {
componentClass: _propTypes2["default"].oneOfType([_propTypes2["default"].element, _propTypes2["default"].string]),
type: _propTypes2["default"].string,
size: _propTypes2["default"].oneOf(['sm', 'md', 'lg']),
onSearch: _propTypes2["default"].func,
onChange: _propTypes2["default"].func,
onBlur: _propTypes2["default"].func,
showClose: _propTypes2["default"].bool,
focusSelect: _propTypes2["default"].bool,
debounceDelay: _propTypes2["default"].number,
maxLength: _propTypes2["default"].number
};
var defaultProps = {
componentClass: 'input',
clsPrefix: 'u-form-control',
type: 'text',
size: 'md'
};
function fixControlledValue(value) {
if (typeof value === 'undefined' || value === null) {
return '';
}
return value;
}
var cutValue = function cutValue(value, maxLength) {
if (maxLength && value) {
value = value.toString().substring(0, maxLength);
}
return value;
};
var FormControl = function (_React$Component) {
_inherits(FormControl, _React$Component);
function FormControl(props) {
_classCallCheck(this, FormControl);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_initialiseProps.call(_this);
var value = typeof props.value === 'undefined' ? cutValue(props.defaultValue, props.maxLength) : cutValue(props.value, props.maxLength);
_this.state = {
showSearch: !props.value,
value: value
};
_this.input = {};
_this.clickClearBtn = false;
return _this;
}
FormControl.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProp) {
if ("value" in nextProp) {
if (nextProp.value !== this.state.value) {
this.setState({
value: nextProp.value
});
}
}
};
FormControl.prototype.render = function render() {
if (this.props.type === "search") {
return this.renderSearch();
}
return this.renderInput();
};
return FormControl;
}(_react2["default"].Component);
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.handleSearchChange = function (e) {
var onChange = _this2.props.onChange;
console.log('hpapaas', this2.input.value)
var value = _this2.input.value;
_this2.setState({
value: value,
showSearch: value == null || value === ""
});
if (onChange) {
onChange(value, e);
}
};
this.handleChange = function (e) {
console.log('jira')
var _props$debounceDelay = _this2.props.debounceDelay,
debounceDelay = _props$debounceDelay === undefined ? 0 : _props$debounceDelay;
var now = new Date().getTime();
if (now - _this2.lastScrollCall < debounceDelay) return;
_this2.lastScrollCall = now;
var onChange = _this2.props.onChange;
var value = _this2.input.value || e.target.value;
console.log('habanova', _this2.input.value || e.target.value)
if (!('value' in _this2.props)) {
_this2.setState({ value: value });
}
if (onChange) {
onChange(value, e);
}
};
this.clearValue = function () {
var _props = _this2.props,
onChange = _props.onChange,
showClose = _props.showClose;
_this2.setState({
showSearch: true,
value: ""
});
if (_this2.e && _this2.e.target) _this2.e.target.value = "";
if (onChange) {
onChange("", _this2.e);
}
if (showClose) {
_this2.blurTime && clearTimeout(_this2.blurTime);
_this2.blurTime = null;
}
_this2.input.focus();
};
this.handleKeyDown = function (e) {
var _props2 = _this2.props,
onSearch = _props2.onSearch,
type = _props2.type,
onKeyDown = _props2.onKeyDown;
if (e.keyCode === 13 && type === "search") {
if (onSearch) {
onSearch(_this2.input.value);
}
}
onKeyDown && onKeyDown(e);
};
this.handleSearch = function (e) {
var onSearch = _this2.props.onSearch;
if (onSearch) onSearch(_this2.input.value);
};
this.handleBlur = function (e) {
var value = _this2.state.value;
var _props3 = _this2.props,
onBlur = _props3.onBlur,
showClose = _props3.showClose;
var _e = _extends({}, e);
_this2.e = _e;
if (onBlur) {
if (showClose && _this2.clickClearBtn) {
_this2.clickClearBtn = false;
onBlur(value, _e, true);
} else {
onBlur(value, _e);
}
}
};
this.handleFocus = function (e) {
var value = _this2.state.value;
var onFocus = _this2.props.onFocus;
if (_this2.props.focusSelect) {
_this2.input.select();
}
if (onFocus) {
onFocus(value, e);
}
};
this.onClearBtnMouseDown = function () {
_this2.clickClearBtn = true;
};
this.renderInput = function () {
var Component = _this2.props.componentClass;
var _props4 = _this2.props,
type = _props4.type,
className = _props4.className,
size = _props4.size,
clsPrefix = _props4.clsPrefix,
onChange = _props4.onChange,
onSearch = _props4.onSearch,
onBlur = _props4.onBlur,
showClose = _props4.showClose,
focusSelect = _props4.focusSelect,
prefix = _props4.prefix,
suffix = _props4.suffix,
others = _objectWithoutProperties(_props4, ['type', 'className', 'size', 'clsPrefix', 'onChange', 'onSearch', 'onBlur', 'showClose', 'focusSelect', 'prefix', 'suffix']);
// input[type="file"] 不应该有类名 .form-control.
var value = _this2.state.value;
var classes = {};
if (size) {
classes['' + size] = true;
}
if (Component === 'textarea') {
Component = _rcTextarea2["default"];
}
var classNames = void 0;
if (type !== 'file') {
classNames = (0, _classnames2["default"])(clsPrefix, classes);
}
if (prefix || suffix) classNames += ' ' + clsPrefix + '-prefix-suffix';
if (className) classNames += ' ' + className;
// 加判断,是否有 前后缀,是否加 wrapper
if (showClose || suffix || prefix) {
return _react2["default"].createElement(
'div',
{ className: (0, _classnames2["default"])(clsPrefix + '-close', clsPrefix + '-affix-wrapper ' + clsPrefix + '-affix-wrapper-' + size, className) },
prefix ? _react2["default"].createElement(
'span',
{ className: clsPrefix + '-simple-prefix' },
prefix
) : '',
_react2["default"].createElement(Component, _extends({}, others, {
type: type,
ref: function ref(el) {
return _this2.input = el;
},
value: fixControlledValue(value),
onChange: _this2.handleChange,
onBlur: _this2.handleBlur,
onFocus: _this2.handleFocus,
className: (0, _classnames2["default"])(classNames),
maxLength: _this2.props.maxLength
})),
showClose && value ? _react2["default"].createElement(
'div',
{ className: clsPrefix + '-suffix has-close', onMouseDown: _this2.onClearBtnMouseDown, onClick: _this2.clearValue },
_react2["default"].createElement(_beeIcon2["default"], { type: 'uf-close-c' })
) : '',
suffix ? _react2["default"].createElement(
'span',
{ className: clsPrefix + '-simple-suffix' },
suffix
) : ''
);
} else {
return _react2["default"].createElement(Component, _extends({}, others, {
type: type,
ref: function ref(el) {
return _this2.input = el;
},
value: fixControlledValue(value),
onChange: _this2.handleChange,
onBlur: _this2.handleBlur,
onFocus: _this2.handleFocus,
className: (0, _classnames2["default"])(classNames),
maxLength: _this2.props.maxLength
}));
}
};
this.renderSearch = function () {
var _props5 = _this2.props,
Component = _props5.componentClass,
type = _props5.type,
className = _props5.className,
size = _props5.size,
clsPrefix = _props5.clsPrefix,
onChange = _props5.onChange,
onSearch = _props5.onSearch,
onBlur = _props5.onBlur,
others = _objectWithoutProperties(_props5, ['componentClass', 'type', 'className', 'size', 'clsPrefix', 'onChange', 'onSearch', 'onBlur']);
// input[type="file"] 不应该有类名 .form-control.
var value = _this2.state.value;
var classes = {};
if (size) {
classes['' + size] = true;
}
classes[clsPrefix + '-search'] = true;
if (type === "search") {
return _react2["default"].createElement(
'div',
{ className: (0, _classnames2["default"])(clsPrefix + '-search', clsPrefix + '-affix-wrapper', className) },
_react2["default"].createElement(Component, _extends({}, others, {
type: type,
ref: function ref(el) {
return _this2.input = el;
},
onChange: _this2.handleSearchChange,
value: fixControlledValue(value),
onKeyDown: _this2.handleKeyDown,
onBlur: _this2.handleBlur,
onFocus: _this2.handleFocus,
className: (0, _classnames2["default"])(clsPrefix, classes),
maxLength: _this2.props.maxLength
})),
_react2["default"].createElement(
'div',
{ className: clsPrefix + '-suffix' },
_react2["default"].createElement(_beeIcon2["default"], { type: 'uf-search', onClick: _this2.handleSearch })
)
);
}
};
};
FormControl.propTypes = propTypes;
FormControl.defaultProps = defaultProps;
exports["default"] = FormControl;
module.exports = exports['default'];
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(216);
var _interopRequireDefault = __webpack_require__(14);
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ResizableTextArea", {
enumerable: true,
get: function get() {
return _ResizableTextArea.default;
}
});
exports.default = void 0;
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(269));
var _createClass2 = _interopRequireDefault(__webpack_require__(270));
var _inherits2 = _interopRequireDefault(__webpack_require__(271));
var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(273));
var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(275));
var React = _interopRequireWildcard(__webpack_require__(1));
var _ResizableTextArea = _interopRequireDefault(__webpack_require__(276));
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var TextArea = /*#__PURE__*/function (_React$Component) {
(0, _inherits2.default)(TextArea, _React$Component);
var _super = _createSuper(TextArea);
function TextArea(props) {
var _this;
(0, _classCallCheck2.default)(this, TextArea);
_this = _super.call(this, props);
_this.focus = function () {
_this.resizableTextArea.textArea.focus();
};
_this.saveTextArea = function (resizableTextArea) {
_this.resizableTextArea = resizableTextArea;
};
_this.handleChange = function (e) {
var onChange = _this.props.onChange;
_this.setValue(e.target.value, function () {
_this.resizableTextArea.resizeTextarea();
});
if (onChange) {
onChange(e);
}
};
_this.handleKeyDown = function (e) {
var _this$props = _this.props,
onPressEnter = _this$props.onPressEnter,
onKeyDown = _this$props.onKeyDown;
if (e.keyCode === 13 && onPressEnter) {
onPressEnter(e);
}
if (onKeyDown) {
onKeyDown(e);
}
};
var value = typeof props.value === 'undefined' || props.value === null ? props.defaultValue : props.value;
_this.state = {
value: value
};
return _this;
}
(0, _createClass2.default)(TextArea, [{
key: "setValue",
value: function setValue(value, callback) {
if (!('value' in this.props)) {
this.setState({
value: value
}, callback);
}
}
}, {
key: "blur",
value: function blur() {
this.resizableTextArea.textArea.blur();
}
}, {
key: "render",
value: function render() {
return React.createElement(_ResizableTextArea.default, Object.assign({}, this.props, {
value: this.state.value,
onKeyDown: this.handleKeyDown,
onChange: this.handleChange,
ref: this.saveTextArea
}));
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps) {
if ('value' in nextProps) {
return {
value: nextProps.value
};
}
return null;
}
}]);
return TextArea;
}(React.Component);
var _default = TextArea;
exports.default = _default;
/***/ }),
/* 269 */
/***/ (function(module, exports) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck;
/***/ }),
/* 270 */
/***/ (function(module, exports) {
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
module.exports = _createClass;
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
var setPrototypeOf = __webpack_require__(272);
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits;
/***/ }),
/* 272 */
/***/ (function(module, exports) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
/***/ }),
/* 273 */
/***/ (function(module, exports, __webpack_require__) {
var _typeof = __webpack_require__(274);
var assertThisInitialized = __webpack_require__(222);
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn;
/***/ }),
/* 274 */
/***/ (function(module, exports) {
function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
function _typeof(obj) {
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return _typeof2(obj);
};
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
};
}
return _typeof(obj);
}
module.exports = _typeof;
/***/ }),
/* 275 */
/***/ (function(module, exports) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(216);
var _interopRequireDefault = __webpack_require__(14);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(__webpack_require__(277));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(269));
var _createClass2 = _interopRequireDefault(__webpack_require__(270));
var _inherits2 = _interopRequireDefault(__webpack_require__(271));
var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(273));
var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(275));
var React = _interopRequireWildcard(__webpack_require__(1));
var _rcResizeObserver = _interopRequireDefault(__webpack_require__(278));
var _omit = _interopRequireDefault(__webpack_require__(292));
var _classnames = _interopRequireDefault(__webpack_require__(5));
var _calculateNodeHeight = _interopRequireDefault(__webpack_require__(295));
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
// eslint-disable-next-line @typescript-eslint/naming-convention
var RESIZE_STATUS;
(function (RESIZE_STATUS) {
RESIZE_STATUS[RESIZE_STATUS["NONE"] = 0] = "NONE";
RESIZE_STATUS[RESIZE_STATUS["RESIZING"] = 1] = "RESIZING";
RESIZE_STATUS[RESIZE_STATUS["RESIZED"] = 2] = "RESIZED";
})(RESIZE_STATUS || (RESIZE_STATUS = {}));
var ResizableTextArea = /*#__PURE__*/function (_React$Component) {
(0, _inherits2.default)(ResizableTextArea, _React$Component);
var _super = _createSuper(ResizableTextArea);
function ResizableTextArea(props) {
var _this;
(0, _classCallCheck2.default)(this, ResizableTextArea);
_this = _super.call(this, props);
_this.saveTextArea = function (textArea) {
_this.textArea = textArea;
};
_this.handleResize = function (size) {
var resizeStatus = _this.state.resizeStatus;
var _this$props = _this.props,
autoSize = _this$props.autoSize,
onResize = _this$props.onResize;
if (resizeStatus !== RESIZE_STATUS.NONE) {
return;
}
if (typeof onResize === 'function') {
onResize(size);
}
if (autoSize) {
_this.resizeOnNextFrame();
}
};
_this.resizeOnNextFrame = function () {
cancelAnimationFrame(_this.nextFrameActionId);
_this.nextFrameActionId = requestAnimationFrame(_this.resizeTextarea);
};
_this.resizeTextarea = function () {
var autoSize = _this.props.autoSize;
if (!autoSize || !_this.textArea) {
return;
}
var minRows = autoSize.minRows,
maxRows = autoSize.maxRows;
var textareaStyles = (0, _calculateNodeHeight.default)(_this.textArea, false, minRows, maxRows);
_this.setState({
textareaStyles: textareaStyles,
resizeStatus: RESIZE_STATUS.RESIZING
}, function () {
cancelAnimationFrame(_this.resizeFrameId);
_this.resizeFrameId = requestAnimationFrame(function () {
_this.setState({
resizeStatus: RESIZE_STATUS.RESIZED
}, function () {
_this.resizeFrameId = requestAnimationFrame(function () {
_this.setState({
resizeStatus: RESIZE_STATUS.NONE
});
_this.fixFirefoxAutoScroll();
});
});
});
});
};
_this.renderTextArea = function () {
var _this$props2 = _this.props,
_this$props2$prefixCl = _this$props2.prefixCls,
prefixCls = _this$props2$prefixCl === void 0 ? 'rc-textarea' : _this$props2$prefixCl,
autoSize = _this$props2.autoSize,
onResize = _this$props2.onResize,
className = _this$props2.className,
disabled = _this$props2.disabled;
var _this$state = _this.state,
textareaStyles = _this$state.textareaStyles,
resizeStatus = _this$state.resizeStatus;
var otherProps = (0, _omit.default)(_this.props, ['prefixCls', 'onPressEnter', 'autoSize', 'defaultValue', 'onResize']);
var cls = (0, _classnames.default)(prefixCls, className, (0, _defineProperty2.default)({}, "".concat(prefixCls, "-disabled"), disabled)); // Fix https://github.com/ant-design/ant-design/issues/6776
// Make sure it could be reset when using form.getFieldDecorator
if ('value' in otherProps) {
otherProps.value = otherProps.value || '';
}
var style = _objectSpread(_objectSpread(_objectSpread({}, _this.props.style), textareaStyles), resizeStatus === RESIZE_STATUS.RESIZING ? // React will warning when mix `overflow` & `overflowY`.
// We need to define this separately.
{
overflowX: 'hidden',
overflowY: 'hidden'
} : null);
return React.createElement(_rcResizeObserver.default, {
onResize: _this.handleResize,
disabled: !(autoSize || onResize)
}, React.createElement("textarea", Object.assign({}, otherProps, {
className: cls,
style: style,
ref: _this.saveTextArea
})));
};
_this.state = {
textareaStyles: {},
resizeStatus: RESIZE_STATUS.NONE
};
return _this;
}
(0, _createClass2.default)(ResizableTextArea, [{
key: "componentDidMount",
value: function componentDidMount() {
this.resizeTextarea();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
// Re-render with the new content then recalculate the height as required.
if (prevProps.value !== this.props.value) {
this.resizeTextarea();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
cancelAnimationFrame(this.nextFrameActionId);
cancelAnimationFrame(this.resizeFrameId);
} // https://github.com/ant-design/ant-design/issues/21870
}, {
key: "fixFirefoxAutoScroll",
value: function fixFirefoxAutoScroll() {
try {
if (document.activeElement === this.textArea) {
var currentStart = this.textArea.selectionStart;
var currentEnd = this.textArea.selectionEnd;
this.textArea.setSelectionRange(currentStart, currentEnd);
}
} catch (e) {// Fix error in Chrome:
// Failed to read the 'selectionStart' property from 'HTMLInputElement'
// http://stackoverflow.com/q/21177489/3040605
}
}
}, {
key: "render",
value: function render() {
return this.renderTextArea();
}
}]);
return ResizableTextArea;
}(React.Component);
var _default = ResizableTextArea;
exports.default = _default;
/***/ }),
/* 277 */
/***/ (function(module, exports) {
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty;
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(216);
var _interopRequireDefault = __webpack_require__(14);
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(279));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(269));
var _createClass2 = _interopRequireDefault(__webpack_require__(270));
var _inherits2 = _interopRequireDefault(__webpack_require__(271));
var _createSuper2 = _interopRequireDefault(__webpack_require__(281));
var React = _interopRequireWildcard(__webpack_require__(1));
var _findDOMNode = _interopRequireDefault(__webpack_require__(287));
var _toArray = _interopRequireDefault(__webpack_require__(288));
var _warning = _interopRequireDefault(__webpack_require__(289));
var _ref = __webpack_require__(290);
var _resizeObserverPolyfill = _interopRequireDefault(__webpack_require__(291));
var INTERNAL_PREFIX_KEY = 'rc-observer-key'; // Still need to be compatible with React 15, we use class component here
var ReactResizeObserver = /*#__PURE__*/function (_React$Component) {
(0, _inherits2.default)(ReactResizeObserver, _React$Component);
var _super = (0, _createSuper2.default)(ReactResizeObserver);
function ReactResizeObserver() {
var _this;
(0, _classCallCheck2.default)(this, ReactResizeObserver);
_this = _super.apply(this, arguments);
_this.resizeObserver = null;
_this.childNode = null;
_this.currentElement = null;
_this.state = {
width: 0,
height: 0,
offsetHeight: 0,
offsetWidth: 0
};
_this.onResize = function (entries) {
var onResize = _this.props.onResize;
var target = entries[0].target;
var _target$getBoundingCl = target.getBoundingClientRect(),
width = _target$getBoundingCl.width,
height = _target$getBoundingCl.height;
var offsetWidth = target.offsetWidth,
offsetHeight = target.offsetHeight;
/**
* Resize observer trigger when content size changed.
* In most case we just care about element size,
* let's use `boundary` instead of `contentRect` here to avoid shaking.
*/
var fixedWidth = Math.floor(width);
var fixedHeight = Math.floor(height);
if (_this.state.width !== fixedWidth || _this.state.height !== fixedHeight || _this.state.offsetWidth !== offsetWidth || _this.state.offsetHeight !== offsetHeight) {
var size = {
width: fixedWidth,
height: fixedHeight,
offsetWidth: offsetWidth,
offsetHeight: offsetHeight
};
_this.setState(size);
if (onResize) {
// defer the callback but not defer to next frame
Promise.resolve().then(function () {
onResize((0, _objectSpread2.default)((0, _objectSpread2.default)({}, size), {}, {
offsetWidth: offsetWidth,
offsetHeight: offsetHeight
}));
});
}
}
};
_this.setChildNode = function (node) {
_this.childNode = node;
};
return _this;
}
(0, _createClass2.default)(ReactResizeObserver, [{
key: "componentDidMount",
value: function componentDidMount() {
this.onComponentUpdated();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
this.onComponentUpdated();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.destroyObserver();
}
}, {
key: "onComponentUpdated",
value: function onComponentUpdated() {
var disabled = this.props.disabled; // Unregister if disabled
if (disabled) {
this.destroyObserver();
return;
} // Unregister if element changed
var element = (0, _findDOMNode.default)(this.childNode || this);
var elementChanged = element !== this.currentElement;
if (elementChanged) {
this.destroyObserver();
this.currentElement = element;
}
if (!this.resizeObserver && element) {
this.resizeObserver = new _resizeObserverPolyfill.default(this.onResize);
this.resizeObserver.observe(element);
}
}
}, {
key: "destroyObserver",
value: function destroyObserver() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
this.resizeObserver = null;
}
}
}, {
key: "render",
value: function render() {
var children = this.props.children;
var childNodes = (0, _toArray.default)(children);
if (childNodes.length > 1) {
(0, _warning.default)(false, 'Find more than one child node with `children` in ResizeObserver. Will only observe first one.');
} else if (childNodes.length === 0) {
(0, _warning.default)(false, '`children` of ResizeObserver is empty. Nothing is in observe.');
return null;
}
var childNode = childNodes[0];
if (React.isValidElement(childNode) && (0, _ref.supportRef)(childNode)) {
var ref = childNode.ref;
childNodes[0] = React.cloneElement(childNode, {
ref: (0, _ref.composeRef)(ref, this.setChildNode)
});
}
return childNodes.length === 1 ? childNodes[0] : childNodes.map(function (node, index) {
if (!React.isValidElement(node) || 'key' in node && node.key !== null) {
return node;
}
return React.cloneElement(node, {
key: "".concat(INTERNAL_PREFIX_KEY, "-").concat(index)
});
});
}
}]);
return ReactResizeObserver;
}(React.Component);
ReactResizeObserver.displayName = 'ResizeObserver';
var _default = ReactResizeObserver;
exports.default = _default;
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(280);
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
module.exports = _objectSpread2;
/***/ }),
/* 280 */
/***/ (function(module, exports) {
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty;
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
var getPrototypeOf = __webpack_require__(282);
var isNativeReflectConstruct = __webpack_require__(283);
var possibleConstructorReturn = __webpack_require__(284);
function _createSuper(Derived) {
var hasNativeReflectConstruct = isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn(this, result);
};
}
module.exports = _createSuper;
/***/ }),
/* 282 */
/***/ (function(module, exports) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
/***/ }),
/* 283 */
/***/ (function(module, exports) {
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
module.exports = _isNativeReflectConstruct;
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
var _typeof = __webpack_require__(285);
var assertThisInitialized = __webpack_require__(286);
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn;
/***/ }),
/* 285 */
/***/ (function(module, exports) {
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return typeof obj;
};
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
module.exports = _typeof;
/***/ }),
/* 286 */
/***/ (function(module, exports) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized;
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = findDOMNode;
var _reactDom = _interopRequireDefault(__webpack_require__(2));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Return if a node is a DOM node. Else will return by `findDOMNode`
*/
function findDOMNode(node) {
if (node instanceof HTMLElement) {
return node;
}
return _reactDom.default.findDOMNode(node);
}
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = toArray;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function toArray(children) {
var ret = [];
_react2['default'].Children.forEach(children, function (c) {
ret.push(c);
});
return ret;
}
module.exports = exports['default'];
/***/ }),
/* 289 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.warning = warning;
exports.note = note;
exports.resetWarned = resetWarned;
exports.call = call;
exports.warningOnce = warningOnce;
exports.noteOnce = noteOnce;
exports.default = void 0;
/* eslint-disable no-console */
var warned = {};
function warning(valid, message) {
// Support uglify
if (process.env.NODE_ENV !== 'production' && !valid && console !== undefined) {
console.error("Warning: ".concat(message));
}
}
function note(valid, message) {
// Support uglify
if (process.env.NODE_ENV !== 'production' && !valid && console !== undefined) {
console.warn("Note: ".concat(message));
}
}
function resetWarned() {
warned = {};
}
function call(method, valid, message) {
if (!valid && !warned[message]) {
method(false, message);
warned[message] = true;
}
}
function warningOnce(valid, message) {
call(warning, valid, message);
}
function noteOnce(valid, message) {
call(note, valid, message);
}
var _default = warningOnce;
/* eslint-enable */
exports.default = _default;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))
/***/ }),
/* 290 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fillRef = fillRef;
exports.composeRef = composeRef;
exports.supportRef = supportRef;
var _reactIs = __webpack_require__(225);
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function fillRef(ref, node) {
if (typeof ref === 'function') {
ref(node);
} else if (_typeof(ref) === 'object' && ref && 'current' in ref) {
ref.current = node;
}
}
/**
* Merge refs into one ref function to support ref passing.
*/
function composeRef() {
for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
refs[_key] = arguments[_key];
}
return function (node) {
refs.forEach(function (ref) {
fillRef(ref, node);
});
};
}
function supportRef(nodeOrComponent) {
var _type$prototype, _nodeOrComponent$prot;
var type = (0, _reactIs.isMemo)(nodeOrComponent) ? nodeOrComponent.type.type : nodeOrComponent.type; // Function component node
if (typeof type === 'function' && !((_type$prototype = type.prototype) === null || _type$prototype === void 0 ? void 0 : _type$prototype.render)) {
return false;
} // Class component
if (typeof nodeOrComponent === 'function' && !((_nodeOrComponent$prot = nodeOrComponent.prototype) === null || _nodeOrComponent$prot === void 0 ? void 0 : _nodeOrComponent$prot.render)) {
return false;
}
return true;
}
/* eslint-enable */
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ResizeObserver = factory());
}(this, (function () { 'use strict';
/**
* A collection of shims that provide minimal functionality of the ES6 collections.
*
* These implementations are not meant to be used outside of the ResizeObserver
* modules as they cover only a limited range of use cases.
*/
/* eslint-disable require-jsdoc, valid-jsdoc */
var MapShim = (function () {
if (typeof Map !== 'undefined') {
return Map;
}
/**
* Returns index in provided array that matches the specified key.
*
* @param {Array<Array>} arr
* @param {*} key
* @returns {number}
*/
function getIndex(arr, key) {
var result = -1;
arr.some(function (entry, index) {
if (entry[0] === key) {
result = index;
return true;
}
return false;
});
return result;
}
return /** @class */ (function () {
function class_1() {
this.__entries__ = [];
}
Object.defineProperty(class_1.prototype, "size", {
/**
* @returns {boolean}
*/
get: function () {
return this.__entries__.length;
},
enumerable: true,
configurable: true
});
/**
* @param {*} key
* @returns {*}
*/
class_1.prototype.get = function (key) {
var index = getIndex(this.__entries__, key);
var entry = this.__entries__[index];
return entry && entry[1];
};
/**
* @param {*} key
* @param {*} value
* @returns {void}
*/
class_1.prototype.set = function (key, value) {
var index = getIndex(this.__entries__, key);
if (~index) {
this.__entries__[index][1] = value;
}
else {
this.__entries__.push([key, value]);
}
};
/**
* @param {*} key
* @returns {void}
*/
class_1.prototype.delete = function (key) {
var entries = this.__entries__;
var index = getIndex(entries, key);
if (~index) {
entries.splice(index, 1);
}
};
/**
* @param {*} key
* @returns {void}
*/
class_1.prototype.has = function (key) {
return !!~getIndex(this.__entries__, key);
};
/**
* @returns {void}
*/
class_1.prototype.clear = function () {
this.__entries__.splice(0);
};
/**
* @param {Function} callback
* @param {*} [ctx=null]
* @returns {void}
*/
class_1.prototype.forEach = function (callback, ctx) {
if (ctx === void 0) { ctx = null; }
for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
var entry = _a[_i];
callback.call(ctx, entry[1], entry[0]);
}
};
return class_1;
}());
})();
/**
* Detects whether window and document objects are available in current environment.
*/
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;
// Returns global object of a current environment.
var global$1 = (function () {
if (typeof global !== 'undefined' && global.Math === Math) {
return global;
}
if (typeof self !== 'undefined' && self.Math === Math) {
return self;
}
if (typeof window !== 'undefined' && window.Math === Math) {
return window;
}
// eslint-disable-next-line no-new-func
return Function('return this')();
})();
/**
* A shim for the requestAnimationFrame which falls back to the setTimeout if
* first one is not supported.
*
* @returns {number} Requests' identifier.
*/
var requestAnimationFrame$1 = (function () {
if (typeof requestAnimationFrame === 'function') {
// It's required to use a bounded function because IE sometimes throws
// an "Invalid calling object" error if rAF is invoked without the global
// object on the left hand side.
return requestAnimationFrame.bind(global$1);
}
return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };
})();
// Defines minimum timeout before adding a trailing call.
var trailingTimeout = 2;
/**
* Creates a wrapper function which ensures that provided callback will be
* invoked only once during the specified delay period.
*
* @param {Function} callback - Function to be invoked after the delay period.
* @param {number} delay - Delay after which to invoke callback.
* @returns {Function}
*/
function throttle (callback, delay) {
var leadingCall = false, trailingCall = false, lastCallTime = 0;
/**
* Invokes the original callback function and schedules new invocation if
* the "proxy" was called during current request.
*
* @returns {void}
*/
function resolvePending() {
if (leadingCall) {
leadingCall = false;
callback();
}
if (trailingCall) {
proxy();
}
}
/**
* Callback invoked after the specified delay. It will further postpone
* invocation of the original function delegating it to the
* requestAnimationFrame.
*
* @returns {void}
*/
function timeoutCallback() {
requestAnimationFrame$1(resolvePending);
}
/**
* Schedules invocation of the original function.
*
* @returns {void}
*/
function proxy() {
var timeStamp = Date.now();
if (leadingCall) {
// Reject immediately following calls.
if (timeStamp - lastCallTime < trailingTimeout) {
return;
}
// Schedule new call to be in invoked when the pending one is resolved.
// This is important for "transitions" which never actually start
// immediately so there is a chance that we might miss one if change
// happens amids the pending invocation.
trailingCall = true;
}
else {
leadingCall = true;
trailingCall = false;
setTimeout(timeoutCallback, delay);
}
lastCallTime = timeStamp;
}
return proxy;
}
// Minimum delay before invoking the update of observers.
var REFRESH_DELAY = 20;
// A list of substrings of CSS properties used to find transition events that
// might affect dimensions of observed elements.
var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];
// Check if MutationObserver is available.
var mutationObserverSupported = typeof MutationObserver !== 'undefined';
/**
* Singleton controller class which handles updates of ResizeObserver instances.
*/
var ResizeObserverController = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserverController.
*
* @private
*/
function ResizeObserverController() {
/**
* Indicates whether DOM listeners have been added.
*
* @private {boolean}
*/
this.connected_ = false;
/**
* Tells that controller has subscribed for Mutation Events.
*
* @private {boolean}
*/
this.mutationEventsAdded_ = false;
/**
* Keeps reference to the instance of MutationObserver.
*
* @private {MutationObserver}
*/
this.mutationsObserver_ = null;
/**
* A list of connected observers.
*
* @private {Array<ResizeObserverSPI>}
*/
this.observers_ = [];
this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
}
/**
* Adds observer to observers list.
*
* @param {ResizeObserverSPI} observer - Observer to be added.
* @returns {void}
*/
ResizeObserverController.prototype.addObserver = function (observer) {
if (!~this.observers_.indexOf(observer)) {
this.observers_.push(observer);
}
// Add listeners if they haven't been added yet.
if (!this.connected_) {
this.connect_();
}
};
/**
* Removes observer from observers list.
*
* @param {ResizeObserverSPI} observer - Observer to be removed.
* @returns {void}
*/
ResizeObserverController.prototype.removeObserver = function (observer) {
var observers = this.observers_;
var index = observers.indexOf(observer);
// Remove observer if it's present in registry.
if (~index) {
observers.splice(index, 1);
}
// Remove listeners if controller has no connected observers.
if (!observers.length && this.connected_) {
this.disconnect_();
}
};
/**
* Invokes the update of observers. It will continue running updates insofar
* it detects changes.
*
* @returns {void}
*/
ResizeObserverController.prototype.refresh = function () {
var changesDetected = this.updateObservers_();
// Continue running updates if changes have been detected as there might
// be future ones caused by CSS transitions.
if (changesDetected) {
this.refresh();
}
};
/**
* Updates every observer from observers list and notifies them of queued
* entries.
*
* @private
* @returns {boolean} Returns "true" if any observer has detected changes in
* dimensions of it's elements.
*/
ResizeObserverController.prototype.updateObservers_ = function () {
// Collect observers that have active observations.
var activeObservers = this.observers_.filter(function (observer) {
return observer.gatherActive(), observer.hasActive();
});
// Deliver notifications in a separate cycle in order to avoid any
// collisions between observers, e.g. when multiple instances of
// ResizeObserver are tracking the same element and the callback of one
// of them changes content dimensions of the observed target. Sometimes
// this may result in notifications being blocked for the rest of observers.
activeObservers.forEach(function (observer) { return observer.broadcastActive(); });
return activeObservers.length > 0;
};
/**
* Initializes DOM listeners.
*
* @private
* @returns {void}
*/
ResizeObserverController.prototype.connect_ = function () {
// Do nothing if running in a non-browser environment or if listeners
// have been already added.
if (!isBrowser || this.connected_) {
return;
}
// Subscription to the "Transitionend" event is used as a workaround for
// delayed transitions. This way it's possible to capture at least the
// final state of an element.
document.addEventListener('transitionend', this.onTransitionEnd_);
window.addEventListener('resize', this.refresh);
if (mutationObserverSupported) {
this.mutationsObserver_ = new MutationObserver(this.refresh);
this.mutationsObserver_.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
else {
document.addEventListener('DOMSubtreeModified', this.refresh);
this.mutationEventsAdded_ = true;
}
this.connected_ = true;
};
/**
* Removes DOM listeners.
*
* @private
* @returns {void}
*/
ResizeObserverController.prototype.disconnect_ = function () {
// Do nothing if running in a non-browser environment or if listeners
// have been already removed.
if (!isBrowser || !this.connected_) {
return;
}
document.removeEventListener('transitionend', this.onTransitionEnd_);
window.removeEventListener('resize', this.refresh);
if (this.mutationsObserver_) {
this.mutationsObserver_.disconnect();
}
if (this.mutationEventsAdded_) {
document.removeEventListener('DOMSubtreeModified', this.refresh);
}
this.mutationsObserver_ = null;
this.mutationEventsAdded_ = false;
this.connected_ = false;
};
/**
* "Transitionend" event handler.
*
* @private
* @param {TransitionEvent} event
* @returns {void}
*/
ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {
var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;
// Detect whether transition may affect dimensions of an element.
var isReflowProperty = transitionKeys.some(function (key) {
return !!~propertyName.indexOf(key);
});
if (isReflowProperty) {
this.refresh();
}
};
/**
* Returns instance of the ResizeObserverController.
*
* @returns {ResizeObserverController}
*/
ResizeObserverController.getInstance = function () {
if (!this.instance_) {
this.instance_ = new ResizeObserverController();
}
return this.instance_;
};
/**
* Holds reference to the controller's instance.
*
* @private {ResizeObserverController}
*/
ResizeObserverController.instance_ = null;
return ResizeObserverController;
}());
/**
* Defines non-writable/enumerable properties of the provided target object.
*
* @param {Object} target - Object for which to define properties.
* @param {Object} props - Properties to be defined.
* @returns {Object} Target object.
*/
var defineConfigurable = (function (target, props) {
for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
var key = _a[_i];
Object.defineProperty(target, key, {
value: props[key],
enumerable: false,
writable: false,
configurable: true
});
}
return target;
});
/**
* Returns the global object associated with provided element.
*
* @param {Object} target
* @returns {Object}
*/
var getWindowOf = (function (target) {
// Assume that the element is an instance of Node, which means that it
// has the "ownerDocument" property from which we can retrieve a
// corresponding global object.
var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;
// Return the local global object if it's not possible extract one from
// provided element.
return ownerGlobal || global$1;
});
// Placeholder of an empty content rectangle.
var emptyRect = createRectInit(0, 0, 0, 0);
/**
* Converts provided string to a number.
*
* @param {number|string} value
* @returns {number}
*/
function toFloat(value) {
return parseFloat(value) || 0;
}
/**
* Extracts borders size from provided styles.
*
* @param {CSSStyleDeclaration} styles
* @param {...string} positions - Borders positions (top, right, ...)
* @returns {number}
*/
function getBordersSize(styles) {
var positions = [];
for (var _i = 1; _i < arguments.length; _i++) {
positions[_i - 1] = arguments[_i];
}
return positions.reduce(function (size, position) {
var value = styles['border-' + position + '-width'];
return size + toFloat(value);
}, 0);
}
/**
* Extracts paddings sizes from provided styles.
*
* @param {CSSStyleDeclaration} styles
* @returns {Object} Paddings box.
*/
function getPaddings(styles) {
var positions = ['top', 'right', 'bottom', 'left'];
var paddings = {};
for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
var position = positions_1[_i];
var value = styles['padding-' + position];
paddings[position] = toFloat(value);
}
return paddings;
}
/**
* Calculates content rectangle of provided SVG element.
*
* @param {SVGGraphicsElement} target - Element content rectangle of which needs
* to be calculated.
* @returns {DOMRectInit}
*/
function getSVGContentRect(target) {
var bbox = target.getBBox();
return createRectInit(0, 0, bbox.width, bbox.height);
}
/**
* Calculates content rectangle of provided HTMLElement.
*
* @param {HTMLElement} target - Element for which to calculate the content rectangle.
* @returns {DOMRectInit}
*/
function getHTMLElementContentRect(target) {
// Client width & height properties can't be
// used exclusively as they provide rounded values.
var clientWidth = target.clientWidth, clientHeight = target.clientHeight;
// By this condition we can catch all non-replaced inline, hidden and
// detached elements. Though elements with width & height properties less
// than 0.5 will be discarded as well.
//
// Without it we would need to implement separate methods for each of
// those cases and it's not possible to perform a precise and performance
// effective test for hidden elements. E.g. even jQuery's ':visible' filter
// gives wrong results for elements with width & height less than 0.5.
if (!clientWidth && !clientHeight) {
return emptyRect;
}
var styles = getWindowOf(target).getComputedStyle(target);
var paddings = getPaddings(styles);
var horizPad = paddings.left + paddings.right;
var vertPad = paddings.top + paddings.bottom;
// Computed styles of width & height are being used because they are the
// only dimensions available to JS that contain non-rounded values. It could
// be possible to utilize the getBoundingClientRect if only it's data wasn't
// affected by CSS transformations let alone paddings, borders and scroll bars.
var width = toFloat(styles.width), height = toFloat(styles.height);
// Width & height include paddings and borders when the 'border-box' box
// model is applied (except for IE).
if (styles.boxSizing === 'border-box') {
// Following conditions are required to handle Internet Explorer which
// doesn't include paddings and borders to computed CSS dimensions.
//
// We can say that if CSS dimensions + paddings are equal to the "client"
// properties then it's either IE, and thus we don't need to subtract
// anything, or an element merely doesn't have paddings/borders styles.
if (Math.round(width + horizPad) !== clientWidth) {
width -= getBordersSize(styles, 'left', 'right') + horizPad;
}
if (Math.round(height + vertPad) !== clientHeight) {
height -= getBordersSize(styles, 'top', 'bottom') + vertPad;
}
}
// Following steps can't be applied to the document's root element as its
// client[Width/Height] properties represent viewport area of the window.
// Besides, it's as well not necessary as the <html> itself neither has
// rendered scroll bars nor it can be clipped.
if (!isDocumentElement(target)) {
// In some browsers (only in Firefox, actually) CSS width & height
// include scroll bars size which can be removed at this step as scroll
// bars are the only difference between rounded dimensions + paddings
// and "client" properties, though that is not always true in Chrome.
var vertScrollbar = Math.round(width + horizPad) - clientWidth;
var horizScrollbar = Math.round(height + vertPad) - clientHeight;
// Chrome has a rather weird rounding of "client" properties.
// E.g. for an element with content width of 314.2px it sometimes gives
// the client width of 315px and for the width of 314.7px it may give
// 314px. And it doesn't happen all the time. So just ignore this delta
// as a non-relevant.
if (Math.abs(vertScrollbar) !== 1) {
width -= vertScrollbar;
}
if (Math.abs(horizScrollbar) !== 1) {
height -= horizScrollbar;
}
}
return createRectInit(paddings.left, paddings.top, width, height);
}
/**
* Checks whether provided element is an instance of the SVGGraphicsElement.
*
* @param {Element} target - Element to be checked.
* @returns {boolean}
*/
var isSVGGraphicsElement = (function () {
// Some browsers, namely IE and Edge, don't have the SVGGraphicsElement
// interface.
if (typeof SVGGraphicsElement !== 'undefined') {
return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };
}
// If it's so, then check that element is at least an instance of the
// SVGElement and that it has the "getBBox" method.
// eslint-disable-next-line no-extra-parens
return function (target) { return (target instanceof getWindowOf(target).SVGElement &&
typeof target.getBBox === 'function'); };
})();
/**
* Checks whether provided element is a document element (<html>).
*
* @param {Element} target - Element to be checked.
* @returns {boolean}
*/
function isDocumentElement(target) {
return target === getWindowOf(target).document.documentElement;
}
/**
* Calculates an appropriate content rectangle for provided html or svg element.
*
* @param {Element} target - Element content rectangle of which needs to be calculated.
* @returns {DOMRectInit}
*/
function getContentRect(target) {
if (!isBrowser) {
return emptyRect;
}
if (isSVGGraphicsElement(target)) {
return getSVGContentRect(target);
}
return getHTMLElementContentRect(target);
}
/**
* Creates rectangle with an interface of the DOMRectReadOnly.
* Spec: https://drafts.fxtf.org/geometry/#domrectreadonly
*
* @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.
* @returns {DOMRectReadOnly}
*/
function createReadOnlyRect(_a) {
var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
// If DOMRectReadOnly is available use it as a prototype for the rectangle.
var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;
var rect = Object.create(Constr.prototype);
// Rectangle's properties are not writable and non-enumerable.
defineConfigurable(rect, {
x: x, y: y, width: width, height: height,
top: y,
right: x + width,
bottom: height + y,
left: x
});
return rect;
}
/**
* Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.
* Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit
*
* @param {number} x - X coordinate.
* @param {number} y - Y coordinate.
* @param {number} width - Rectangle's width.
* @param {number} height - Rectangle's height.
* @returns {DOMRectInit}
*/
function createRectInit(x, y, width, height) {
return { x: x, y: y, width: width, height: height };
}
/**
* Class that is responsible for computations of the content rectangle of
* provided DOM element and for keeping track of it's changes.
*/
var ResizeObservation = /** @class */ (function () {
/**
* Creates an instance of ResizeObservation.
*
* @param {Element} target - Element to be observed.
*/
function ResizeObservation(target) {
/**
* Broadcasted width of content rectangle.
*
* @type {number}
*/
this.broadcastWidth = 0;
/**
* Broadcasted height of content rectangle.
*
* @type {number}
*/
this.broadcastHeight = 0;
/**
* Reference to the last observed content rectangle.
*
* @private {DOMRectInit}
*/
this.contentRect_ = createRectInit(0, 0, 0, 0);
this.target = target;
}
/**
* Updates content rectangle and tells whether it's width or height properties
* have changed since the last broadcast.
*
* @returns {boolean}
*/
ResizeObservation.prototype.isActive = function () {
var rect = getContentRect(this.target);
this.contentRect_ = rect;
return (rect.width !== this.broadcastWidth ||
rect.height !== this.broadcastHeight);
};
/**
* Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
* from the corresponding properties of the last observed content rectangle.
*
* @returns {DOMRectInit} Last observed content rectangle.
*/
ResizeObservation.prototype.broadcastRect = function () {
var rect = this.contentRect_;
this.broadcastWidth = rect.width;
this.broadcastHeight = rect.height;
return rect;
};
return ResizeObservation;
}());
var ResizeObserverEntry = /** @class */ (function () {
/**
* Creates an instance of ResizeObserverEntry.
*
* @param {Element} target - Element that is being observed.
* @param {DOMRectInit} rectInit - Data of the element's content rectangle.
*/
function ResizeObserverEntry(target, rectInit) {
var contentRect = createReadOnlyRect(rectInit);
// According to the specification following properties are not writable
// and are also not enumerable in the native implementation.
//
// Property accessors are not being used as they'd require to define a
// private WeakMap storage which may cause memory leaks in browsers that
// don't support this type of collections.
defineConfigurable(this, { target: target, contentRect: contentRect });
}
return ResizeObserverEntry;
}());
var ResizeObserverSPI = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserver.
*
* @param {ResizeObserverCallback} callback - Callback function that is invoked
* when one of the observed elements changes it's content dimensions.
* @param {ResizeObserverController} controller - Controller instance which
* is responsible for the updates of observer.
* @param {ResizeObserver} callbackCtx - Reference to the public
* ResizeObserver instance which will be passed to callback function.
*/
function ResizeObserverSPI(callback, controller, callbackCtx) {
/**
* Collection of resize observations that have detected changes in dimensions
* of elements.
*
* @private {Array<ResizeObservation>}
*/
this.activeObservations_ = [];
/**
* Registry of the ResizeObservation instances.
*
* @private {Map<Element, ResizeObservation>}
*/
this.observations_ = new MapShim();
if (typeof callback !== 'function') {
throw new TypeError('The callback provided as parameter 1 is not a function.');
}
this.callback_ = callback;
this.controller_ = controller;
this.callbackCtx_ = callbackCtx;
}
/**
* Starts observing provided element.
*
* @param {Element} target - Element to be observed.
* @returns {void}
*/
ResizeObserverSPI.prototype.observe = function (target) {
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
// Do nothing if current environment doesn't have the Element interface.
if (typeof Element === 'undefined' || !(Element instanceof Object)) {
return;
}
if (!(target instanceof getWindowOf(target).Element)) {
throw new TypeError('parameter 1 is not of type "Element".');
}
var observations = this.observations_;
// Do nothing if element is already being observed.
if (observations.has(target)) {
return;
}
observations.set(target, new ResizeObservation(target));
this.controller_.addObserver(this);
// Force the update of observations.
this.controller_.refresh();
};
/**
* Stops observing provided element.
*
* @param {Element} target - Element to stop observing.
* @returns {void}
*/
ResizeObserverSPI.prototype.unobserve = function (target) {
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
// Do nothing if current environment doesn't have the Element interface.
if (typeof Element === 'undefined' || !(Element instanceof Object)) {
return;
}
if (!(target instanceof getWindowOf(target).Element)) {
throw new TypeError('parameter 1 is not of type "Element".');
}
var observations = this.observations_;
// Do nothing if element is not being observed.
if (!observations.has(target)) {
return;
}
observations.delete(target);
if (!observations.size) {
this.controller_.removeObserver(this);
}
};
/**
* Stops observing all elements.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.disconnect = function () {
this.clearActive();
this.observations_.clear();
this.controller_.removeObserver(this);
};
/**
* Collects observation instances the associated element of which has changed
* it's content rectangle.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.gatherActive = function () {
var _this = this;
this.clearActive();
this.observations_.forEach(function (observation) {
if (observation.isActive()) {
_this.activeObservations_.push(observation);
}
});
};
/**
* Invokes initial callback function with a list of ResizeObserverEntry
* instances collected from active resize observations.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.broadcastActive = function () {
// Do nothing if observer doesn't have active observations.
if (!this.hasActive()) {
return;
}
var ctx = this.callbackCtx_;
// Create ResizeObserverEntry instance for every active observation.
var entries = this.activeObservations_.map(function (observation) {
return new ResizeObserverEntry(observation.target, observation.broadcastRect());
});
this.callback_.call(ctx, entries, ctx);
this.clearActive();
};
/**
* Clears the collection of active observations.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.clearActive = function () {
this.activeObservations_.splice(0);
};
/**
* Tells whether observer has active observations.
*
* @returns {boolean}
*/
ResizeObserverSPI.prototype.hasActive = function () {
return this.activeObservations_.length > 0;
};
return ResizeObserverSPI;
}());
// Registry of internal observers. If WeakMap is not available use current shim
// for the Map collection as it has all required methods and because WeakMap
// can't be fully polyfilled anyway.
var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();
/**
* ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
* exposing only those methods and properties that are defined in the spec.
*/
var ResizeObserver = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserver.
*
* @param {ResizeObserverCallback} callback - Callback that is invoked when
* dimensions of the observed elements change.
*/
function ResizeObserver(callback) {
if (!(this instanceof ResizeObserver)) {
throw new TypeError('Cannot call a class as a function.');
}
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
var controller = ResizeObserverController.getInstance();
var observer = new ResizeObserverSPI(callback, controller, this);
observers.set(this, observer);
}
return ResizeObserver;
}());
// Expose public methods of ResizeObserver.
[
'observe',
'unobserve',
'disconnect'
].forEach(function (method) {
ResizeObserver.prototype[method] = function () {
var _a;
return (_a = observers.get(this))[method].apply(_a, arguments);
};
});
var index = (function () {
// Export existing implementation if available.
if (typeof global$1.ResizeObserver !== 'undefined') {
return global$1.ResizeObserver;
}
return ResizeObserver;
})();
return index;
})));
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = __webpack_require__(293);
var _extends3 = _interopRequireDefault(_extends2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function omit(obj, fields) {
var shallowCopy = (0, _extends3["default"])({}, obj);
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
delete shallowCopy[key];
}
return shallowCopy;
}
exports["default"] = omit;
module.exports = exports['default'];
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _assign = __webpack_require__(294);
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _assign2.default || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(159), __esModule: true };
/***/ }),
/* 295 */
/***/ (function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.calculateNodeStyling = calculateNodeStyling;
exports.default = calculateNodeHeight;
// Thanks to https://github.com/andreypopp/react-textarea-autosize/
/**
* calculateNodeHeight(uiTextNode, useCache = false)
*/
var HIDDEN_TEXTAREA_STYLE = "\n min-height:0 !important;\n max-height:none !important;\n height:0 !important;\n visibility:hidden !important;\n overflow:hidden !important;\n position:absolute !important;\n z-index:-1000 !important;\n top:0 !important;\n right:0 !important\n";
var SIZING_STYLE = ['letter-spacing', 'line-height', 'padding-top', 'padding-bottom', 'font-family', 'font-weight', 'font-size', 'font-variant', 'text-rendering', 'text-transform', 'width', 'text-indent', 'padding-left', 'padding-right', 'border-width', 'box-sizing'];
var computedStyleCache = {};
var hiddenTextarea;
function calculateNodeStyling(node) {
var useCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var nodeRef = node.getAttribute('id') || node.getAttribute('data-reactid') || node.getAttribute('name');
if (useCache && computedStyleCache[nodeRef]) {
return computedStyleCache[nodeRef];
}
var style = window.getComputedStyle(node);
var boxSizing = style.getPropertyValue('box-sizing') || style.getPropertyValue('-moz-box-sizing') || style.getPropertyValue('-webkit-box-sizing');
var paddingSize = parseFloat(style.getPropertyValue('padding-bottom')) + parseFloat(style.getPropertyValue('padding-top'));
var borderSize = parseFloat(style.getPropertyValue('border-bottom-width')) + parseFloat(style.getPropertyValue('border-top-width'));
var sizingStyle = SIZING_STYLE.map(function (name) {
return "".concat(name, ":").concat(style.getPropertyValue(name));
}).join(';');
var nodeInfo = {
sizingStyle: sizingStyle,
paddingSize: paddingSize,
borderSize: borderSize,
boxSizing: boxSizing
};
if (useCache && nodeRef) {
computedStyleCache[nodeRef] = nodeInfo;
}
return nodeInfo;
}
function calculateNodeHeight(uiTextNode) {
var useCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var minRows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var maxRows = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
if (!hiddenTextarea) {
hiddenTextarea = document.createElement('textarea');
hiddenTextarea.setAttribute('tab-index', '-1');
hiddenTextarea.setAttribute('aria-hidden', 'true');
document.body.appendChild(hiddenTextarea);
} // Fix wrap="off" issue
// https://github.com/ant-design/ant-design/issues/6577
if (uiTextNode.getAttribute('wrap')) {
hiddenTextarea.setAttribute('wrap', uiTextNode.getAttribute('wrap'));
} else {
hiddenTextarea.removeAttribute('wrap');
} // Copy all CSS properties that have an impact on the height of the content in
// the textbox
var _calculateNodeStyling = calculateNodeStyling(uiTextNode, useCache),
paddingSize = _calculateNodeStyling.paddingSize,
borderSize = _calculateNodeStyling.borderSize,
boxSizing = _calculateNodeStyling.boxSizing,
sizingStyle = _calculateNodeStyling.sizingStyle; // Need to have the overflow attribute to hide the scrollbar otherwise
// text-lines will not calculated properly as the shadow will technically be
// narrower for content
hiddenTextarea.setAttribute('style', "".concat(sizingStyle, ";").concat(HIDDEN_TEXTAREA_STYLE));
hiddenTextarea.value = uiTextNode.value || uiTextNode.placeholder || '';
var minHeight = Number.MIN_SAFE_INTEGER;
var maxHeight = Number.MAX_SAFE_INTEGER;
var height = hiddenTextarea.scrollHeight;
var overflowY;
if (boxSizing === 'border-box') {
// border-box: add border, since height = content + padding + border
height += borderSize;
} else if (boxSizing === 'content-box') {
// remove padding, since height = content
height -= paddingSize;
}
if (minRows !== null || maxRows !== null) {
// measure height of a textarea with a single row
hiddenTextarea.value = ' ';
var singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;
if (minRows !== null) {
minHeight = singleRowHeight * minRows;
if (boxSizing === 'border-box') {
minHeight = minHeight + paddingSize + borderSize;
}
height = Math.max(minHeight, height);
}
if (maxRows !== null) {
maxHeight = singleRowHeight * maxRows;
if (boxSizing === 'border-box') {
maxHeight = maxHeight + paddingSize + borderSize;
}
overflowY = height > maxHeight ? '' : 'hidden';
height = Math.min(maxHeight, height);
}
}
return {
height: height,
minHeight: minHeight,
maxHeight: maxHeight,
overflowY: overflowY
};
}
/***/ }),
/* 296 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _Tree = __webpack_require__(297);
var _Tree2 = _interopRequireDefault(_Tree);
var _TreeNode = __webpack_require__(298);
var _TreeNode2 = _interopRequireDefault(_TreeNode);
var _openAnimation = __webpack_require__(303);
var _openAnimation2 = _interopRequireDefault(_openAnimation);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var TreeProps = {
showLine: _propTypes2['default'].bool,
className: _propTypes2['default'].string,
/** 是否支持多选 */
multiple: _propTypes2['default'].bool,
/** 是否自动展开父节点 */
autoExpandParent: _propTypes2['default'].bool,
/** checkable状态下节点选择完全受控父子节点选中状态不再关联*/
checkStrictly: _propTypes2['default'].bool,
/** 是否支持选中 */
checkable: _propTypes2['default'].bool,
/** 默认展开所有树节点 */
defaultExpandAll: _propTypes2['default'].bool,
/** 默认展开指定的树节点 */
defaultExpandedKeys: _propTypes2['default'].array,
/** (受控)展开指定的树节点 */
expandedKeys: _propTypes2['default'].array,
/** (受控)选中复选框的树节点 */
checkedKeys: _propTypes2['default'].oneOfType([_propTypes2['default'].array, _propTypes2['default'].object]),
/** 默认选中复选框的树节点 */
defaultCheckedKeys: _propTypes2['default'].array,
/** (受控)设置选中的树节点 */
selectedKeys: _propTypes2['default'].array,
/** 默认选中的树节点 */
defaultSelectedKeys: _propTypes2['default'].array,
/** 展开/收起节点时触发 */
onExpand: _propTypes2['default'].func,
/** 点击复选框触发 */
onCheck: _propTypes2['default'].func,
/** 点击树节点触发 */
onSelect: _propTypes2['default'].func,
/** filter some AntTreeNodes as you need. it should return true */
filterAntTreeNode: _propTypes2['default'].func,
/** 异步加载数据 */
loadData: _propTypes2['default'].func,
/** 响应右键点击 */
onRightClick: _propTypes2['default'].func,
/** 设置节点可拖拽IE>8*/
draggable: _propTypes2['default'].bool,
/** 开始拖拽时调用 */
onDragStart: _propTypes2['default'].func,
/** dragenter 触发时调用 */
onDragEnter: _propTypes2['default'].func,
/** dragover 触发时调用 */
onDragOver: _propTypes2['default'].func,
/** dragleave 触发时调用 */
onDragLeave: _propTypes2['default'].func,
/** drop 触发时调用 */
onDrop: _propTypes2['default'].func,
style: _react2['default'].CSSProperties,
prefixCls: _propTypes2['default'].string,
filterTreeNode: _propTypes2['default'].func
};
var defaultProps = {
prefixCls: 'u-tree',
checkable: false,
showIcon: false,
openAnimation: _openAnimation2['default']
};
var Tree = function (_Component) {
_inherits(Tree, _Component);
function Tree() {
_classCallCheck(this, Tree);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
Tree.prototype.render = function render() {
var props = this.props;
var checkable = props.checkable;
return _react2['default'].createElement(
_Tree2['default'],
_extends({}, props, {
checkable: checkable ? _react2['default'].createElement('span', { className: props.prefixCls + '-checkbox-inner' }) : checkable
}),
this.props.children
);
};
return Tree;
}(_react.Component);
Tree.TreeNode = _TreeNode2['default'];
Tree.TreeProps = TreeProps;
Tree.defaultProps = defaultProps;
exports['default'] = Tree;
module.exports = exports['default'];
/***/ }),
/* 297 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _TreeNode = __webpack_require__(298);
var _TreeNode2 = _interopRequireDefault(_TreeNode);
var _infiniteScroll = __webpack_require__(300);
var _infiniteScroll2 = _interopRequireDefault(_infiniteScroll);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _util = __webpack_require__(299);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _tinperBeeCore = __webpack_require__(27);
var _config = __webpack_require__(301);
var _config2 = _interopRequireDefault(_config);
var _createStore = __webpack_require__(302);
var _createStore2 = _interopRequireDefault(_createStore);
var _omit = __webpack_require__(292);
var _omit2 = _interopRequireDefault(_omit);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /* eslint no-console:0 */
function noop() {}
var Tree = function (_React$Component) {
_inherits(Tree, _React$Component);
function Tree(props) {
_classCallCheck(this, Tree);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_initialiseProps.call(_this);
['onKeyDown', 'onCheck', "onUlFocus", "_focusDom", "onUlMouseEnter", "onUlMouseLeave"].forEach(function (m) {
_this[m] = _this[m].bind(_this);
});
_this.contextmenuKeys = [];
_this.latestTreeNode = {};
_this.checkedKeysChange = true;
_this.selectKeyDomPos = '0-0';
_this.state = {
expandedKeys: _this.getDefaultExpandedKeys(props),
checkedKeys: _this.getDefaultCheckedKeys(props),
selectedKeys: _this.getDefaultSelectedKeys(props),
dragNodesKeys: '',
dragOverNodeKey: '',
dropNodeKey: '',
focusKey: '', //上下箭头选择树节点时用于标识focus状态
treeData: [], //Tree结构数组(全量)
flatTreeData: [], //一维数组(全量)
prevProps: null
};
//默认显示20条rowsInView根据定高算的。在非固定高下这个只是一个大概的值。
_this.rowsInView = _config2['default'].defaultRowsInView;
//一次加载多少数据
_this.loadCount = _config2['default'].loadBuffer ? _this.rowsInView + _config2['default'].loadBuffer * 2 : 16;
_this.flatTreeKeysMap = {}; //存储所有 key-value 的映射,方便获取各节点信息
_this.startIndex = 0;
_this.endIndex = _this.startIndex + _this.loadCount;
_this.cacheTreeNodes = []; //缓存 treenode 节点数组
_this.store = (0, _createStore2['default'])({ rowHeight: 24 }); //rowHeight 树节点的高度,此变量在滚动加载场景很关键
_this.latestState = null;
return _this;
}
Tree.prototype.componentDidMount = function componentDidMount() {
// 此处为了区分数据是不是异步渲染的prevProps 作为标识
if (this.hasTreeNode()) {
this.setState({
prevProps: this.props
});
}
// ncc制造树参照包含下级需求checkStrictly 动态改变后,拿到组件内部属性 this.checkedKeys
if (this.props._getTreeObj) {
this.props._getTreeObj(this);
}
this.calculateRowHeight();
};
// 判断初始化挂载时,有没有渲染树节点
Tree.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
var _props = this.props,
treeData = _props.treeData,
lazyLoad = _props.lazyLoad;
var sliceTreeList = [];
//启用懒加载,把 Tree 结构拍平,为后续动态截取数据做准备
if (lazyLoad) {
var flatTreeData = this.deepTraversal(treeData);
flatTreeData.forEach(function (element) {
if (sliceTreeList.length >= _this2.loadCount) return;
sliceTreeList.push(element);
});
this.handleTreeListChange(sliceTreeList);
this.setState({
flatTreeData: flatTreeData
});
} else {
this.setState({
treeData: treeData
});
}
};
Tree.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var flatTreeDataDone = false; //已经更新过flatTree
var startIndex = this.startIndex,
endIndex = this.endIndex,
props = this.props,
state = this.state;
var prevProps = state.prevProps;
var expandedKeys = this.getDefaultExpandedKeys(nextProps, true);
var checkedKeys = this.getDefaultCheckedKeys(nextProps, true);
var selectedKeys = this.getDefaultSelectedKeys(nextProps, true);
var st = {
prevProps: nextProps
};
// 用于记录这次data内容有没有变化
this.dataChange = false;
function needSync(name) {
return !prevProps && name in nextProps || prevProps && prevProps[name] !== nextProps[name];
}
// ================ expandedKeys =================
if (needSync('expandedKeys') || prevProps && needSync('autoExpandParent') || prevProps && prevProps['expandedKeys'] !== expandedKeys) {
st.expandedKeys = expandedKeys;
} else if (!prevProps && props.defaultExpandAll || !prevProps && props.defaultExpandedKeys) {
st.expandedKeys = this.getDefaultExpandedKeys(nextProps);
}
if (st.expandedKeys) {
//缓存 expandedKeys
this.cacheExpandedKeys = new Set(expandedKeys);
if (nextProps.lazyLoad) {
var flatTreeData = this.deepTraversal(nextProps.treeData);
this.cacheExpandedKeys = null;
st.flatTreeData = flatTreeData;
var newTreeList = flatTreeData.slice(startIndex, endIndex);
this.handleTreeListChange(newTreeList, startIndex, endIndex);
flatTreeDataDone = true;
}
}
// ================ checkedKeys =================
if (checkedKeys) {
if (nextProps.checkedKeys === this.props.checkedKeys) {
this.checkedKeysChange = false;
} else {
this.checkedKeysChange = true;
}
st.checkedKeys = checkedKeys;
}
// ================ selectedKeys =================
if (selectedKeys) {
st.selectedKeys = selectedKeys;
}
// ================ treeData =================
if (nextProps.hasOwnProperty('treeData') && nextProps.treeData !== this.props.treeData) {
this.dataChange = true;
//treeData更新时需要重新处理一次数据
if (nextProps.lazyLoad) {
if (!flatTreeDataDone) {
var _flatTreeData = this.deepTraversal(nextProps.treeData);
st.flatTreeData = _flatTreeData;
var _newTreeList = _flatTreeData.slice(startIndex, endIndex);
this.handleTreeListChange(_newTreeList, startIndex, endIndex);
}
} else {
st.treeData = nextProps.treeData;
}
}
// ================ children =================
if (nextProps.children !== this.props.children) {
this.dataChange = true;
}
this.setState(st);
};
Tree.prototype.componentDidUpdate = function componentDidUpdate() {
if (!this.hasCalculateRowHeight) {
this.calculateRowHeight();
}
};
Tree.prototype.onDragStart = function onDragStart(e, treeNode) {
this.dragNode = treeNode;
this.dragNodesKeys = this.getDragNodes(treeNode);
var st = {
dragNodesKeys: this.dragNodesKeys
};
var expandedKeys = this.getExpandedKeys(treeNode, false);
if (expandedKeys) {
// Controlled expand, save and then reset
this.getRawExpandedKeys();
st.expandedKeys = expandedKeys;
}
this.setState(st);
this.props.onDragStart({
event: e,
node: treeNode
});
this._dropTrigger = false;
};
Tree.prototype.onDragEnterGap = function onDragEnterGap(e, treeNode) {
var offsetTop = (0, _util.getOffset)(treeNode.selectHandle).top;
var offsetHeight = treeNode.selectHandle.offsetHeight;
var pageY = e.pageY;
var gapHeight = 2;
if (pageY > offsetTop + offsetHeight - gapHeight) {
this.dropPosition = 1;
return 1;
}
if (pageY < offsetTop + gapHeight) {
this.dropPosition = -1;
return -1;
}
this.dropPosition = 0;
return 0;
};
Tree.prototype.onDragEnter = function onDragEnter(e, treeNode) {
var enterGap = this.onDragEnterGap(e, treeNode);
if (this.dragNode.props.eventKey === treeNode.props.eventKey && enterGap === 0) {
this.setState({
dragOverNodeKey: ''
});
return;
}
var st = {
dragOverNodeKey: treeNode.props.eventKey
};
var expandedKeys = this.getExpandedKeys(treeNode, true);
if (expandedKeys) {
this.getRawExpandedKeys();
st.expandedKeys = expandedKeys;
}
this.setState(st);
this.props.onDragEnter({
event: e,
node: treeNode,
expandedKeys: expandedKeys && [].concat(_toConsumableArray(expandedKeys)) || [].concat(_toConsumableArray(this.state.expandedKeys))
});
};
Tree.prototype.onDragOver = function onDragOver(e, treeNode) {
this.props.onDragOver({
event: e,
node: treeNode
});
};
Tree.prototype.onDragLeave = function onDragLeave(e, treeNode) {
this.props.onDragLeave({
event: e,
node: treeNode
});
};
Tree.prototype.onDrop = function onDrop(e, treeNode) {
var key = treeNode.props.eventKey;
this.setState({
dragOverNodeKey: '',
dropNodeKey: key
});
if (this.dragNodesKeys.indexOf(key) > -1) {
if (console.warn) {
console.warn('can not drop to dragNode(include it\'s children node)');
}
return false;
}
var posArr = treeNode.props.pos.split('-');
var res = {
event: e,
node: treeNode,
dragNode: this.dragNode,
dragNodesKeys: [].concat(_toConsumableArray(this.dragNodesKeys)),
dropPosition: this.dropPosition + Number(posArr[posArr.length - 1])
};
if (this.dropPosition !== 0) {
res.dropToGap = true;
}
if ('expandedKeys' in this.props) {
res.rawExpandedKeys = [].concat(_toConsumableArray(this._rawExpandedKeys)) || [].concat(_toConsumableArray(this.state.expandedKeys));
}
this.props.onDrop(res);
this._dropTrigger = true;
};
Tree.prototype.onDragEnd = function onDragEnd(e, treeNode) {
this.setState({
dragOverNodeKey: ''
});
this.props.onDragEnd({
event: e,
node: treeNode
});
};
/**
*
*
* @param {*} treeNode 当前操作的节点
* @param {*} keyType 键盘事件通用的key类型 left 为收起right为展开
* @returns
* @memberof Tree
*/
Tree.prototype.onExpand = function onExpand(treeNode, keyType) {
var _this3 = this;
var _props2 = this.props,
treeData = _props2.treeData,
lazyLoad = _props2.lazyLoad;
var expanded = !treeNode.props.expanded;
this.latestState = expanded;
this.latestTreeNode = treeNode.props;
var controlled = 'expandedKeys' in this.props;
var expandedKeys = [].concat(_toConsumableArray(this.state.expandedKeys));
var index = expandedKeys.indexOf(treeNode.props.eventKey);
if (keyType == 'left') {
expanded = false;
} else if (keyType == 'right') {
expanded = true;
}
if (expanded && index === -1) {
expandedKeys.push(treeNode.props.eventKey);
} else if (!expanded && index > -1) {
expandedKeys.splice(index, 1);
}
if (!controlled) {
this.setState({
expandedKeys: expandedKeys
});
}
this.props.onExpand(expandedKeys, {
node: treeNode,
expanded: expanded
});
// after data loaded, need set new expandedKeys
if (expanded && this.props.loadData) {
return this.props.loadData(treeNode).then(function () {
if (!controlled) {
_this3.setState({
expandedKeys: expandedKeys
});
}
});
}
//收起和展开时,缓存 expandedKeys
this.cacheExpandedKeys = new Set(expandedKeys);
//启用懒加载,把 Tree 结构拍平,为后续动态截取数据做准备
if (lazyLoad) {
var flatTreeData = this.deepTraversal(treeData);
this.cacheExpandedKeys = null;
this.setState({
flatTreeData: flatTreeData
});
}
};
Tree.prototype.onCheck = function onCheck(treeNode) {
var _this4 = this;
var checked = !treeNode.props.checked;
if (treeNode.props.halfChecked) {
checked = true;
}
var key = treeNode.props.eventKey;
var checkedKeys = [].concat(_toConsumableArray(this.state.checkedKeys));
var index = checkedKeys.indexOf(key);
var newSt = {
event: 'check',
node: treeNode,
checked: checked
};
if (this.props.checkStrictly) {
var rsCheckedKeys = [];
if (checked && index === -1) {
checkedKeys.push(key);
// rsCheckedKeys.push(key);//onCheck第一个参数的key不对
}
if (!checked && index > -1) {
checkedKeys.splice(index, 1);
}
this.treeNodesStates[treeNode.props.pos].checked = checked;
newSt.checkedNodes = [];
var childs = this.props.children;
var _props3 = this.props,
renderTreeNodes = _props3.renderTreeNodes,
treeData = _props3.treeData;
if (renderTreeNodes && treeData) {
childs = renderTreeNodes(treeData);
}
(0, _util.loopAllChildren)(childs, function (item, ind, pos, keyOrPos) {
if (checkedKeys.indexOf(keyOrPos) !== -1) {
newSt.checkedNodes.push(item);
rsCheckedKeys.push(keyOrPos);
}
});
if (!('checkedKeys' in this.props)) {
this.setState({
checkedKeys: rsCheckedKeys
});
}
var halfChecked = this.props.checkedKeys ? this.props.checkedKeys.halfChecked : [];
this.props.onCheck((0, _util.getStrictlyValue)(rsCheckedKeys, halfChecked), newSt);
} else {
if (checked && index === -1) {
this.treeNodesStates[treeNode.props.pos].checked = true;
var checkedPositions = [];
Object.keys(this.treeNodesStates).forEach(function (i) {
if (_this4.treeNodesStates[i].checked) {
checkedPositions.push(i);
}
});
(0, _util.handleCheckState)(this.treeNodesStates, (0, _util.filterParentPosition)(checkedPositions), true);
}
if (!checked) {
this.treeNodesStates[treeNode.props.pos].checked = false;
this.treeNodesStates[treeNode.props.pos].halfChecked = false;
(0, _util.handleCheckState)(this.treeNodesStates, [treeNode.props.pos], false);
}
var checkKeys = (0, _util.getCheck)(this.treeNodesStates);
newSt.checkedNodes = checkKeys.checkedNodes;
newSt.checkedNodesPositions = checkKeys.checkedNodesPositions;
newSt.halfCheckedKeys = checkKeys.halfCheckedKeys;
this.checkKeys = checkKeys;
this._checkedKeys = checkedKeys = checkKeys.checkedKeys;
if (!('checkedKeys' in this.props)) {
this.setState({
checkedKeys: checkedKeys
});
}
this.props.onCheck(checkedKeys, newSt);
}
};
Tree.prototype.onSelect = function onSelect(treeNode) {
var props = this.props;
var selectedKeys = [].concat(_toConsumableArray(this.state.selectedKeys));
var eventKey = treeNode.props.eventKey || treeNode.key;
var index = selectedKeys.indexOf(eventKey);
var selected = void 0;
//cancelUnSelect为true时第二次点击时不取消选中
if (props.cancelUnSelect) {
if (index == -1) {
selected = true;
if (!props.multiple) {
selectedKeys.length = 0;
}
selectedKeys.push(eventKey);
}
} else {
if (index !== -1) {
selected = false;
selectedKeys.splice(index, 1);
} else {
selected = true;
if (!props.multiple) {
selectedKeys.length = 0;
}
selectedKeys.push(eventKey);
}
}
var selectedNodes = [];
if (selectedKeys.length) {
var treeNodes = this.props.children || treeNode.props.root.cacheTreeNodes;
(0, _util.loopAllChildren)(treeNodes, function (item) {
if (selectedKeys.indexOf(item.key) !== -1) {
selectedNodes.push(item);
}
});
}
var newSt = {
event: 'select',
node: treeNode,
selected: selected,
selectedNodes: selectedNodes
};
if (!('selectedKeys' in this.props)) {
this.setState({
selectedKeys: selectedKeys
});
}
this.setState({
focusKey: ''
});
props.onSelect(selectedKeys, newSt);
};
Tree.prototype.onDoubleClick = function onDoubleClick(treeNode) {
var props = this.props;
var eventKey = treeNode.props.eventKey;
var newSt = {
event: 'dblclick',
node: treeNode
};
if (props.expandWhenDoubleClick) {
this.onExpand(treeNode);
}
props.onDoubleClick(eventKey, newSt);
};
Tree.prototype.onMouseEnter = function onMouseEnter(e, treeNode) {
this.props.onMouseEnter({
event: e,
node: treeNode
});
};
Tree.prototype.onMouseLeave = function onMouseLeave(e, treeNode) {
this.props.onMouseLeave({
event: e,
node: treeNode
});
};
Tree.prototype.onContextMenu = function onContextMenu(e, treeNode) {
var selectedKeys = [].concat(_toConsumableArray(this.state.selectedKeys));
var eventKey = treeNode.props.eventKey;
if (this.contextmenuKeys.indexOf(eventKey) === -1) {
this.contextmenuKeys.push(eventKey);
}
this.contextmenuKeys.forEach(function (key) {
var index = selectedKeys.indexOf(key);
if (index !== -1) {
selectedKeys.splice(index, 1);
}
});
if (selectedKeys.indexOf(eventKey) === -1) {
selectedKeys.push(eventKey);
}
this.setState({
selectedKeys: selectedKeys
});
this.props.onRightClick({
event: e,
node: treeNode
});
};
Tree.prototype.getTreeNode = function getTreeNode() {
var props = this.props;
};
Tree.prototype.goDown = function goDown(currentPos, currentIndex, e, treeNode) {
var props = this.props;
var state = this.state;
var treeChildren = props.children ? props.children : this.cacheTreeNodes; //最终渲染在 Tree 标签中的子节点
var nextIndex = parseInt(currentIndex) + 1;
var nextPos = void 0,
backNextPos = void 0;
var nextTreeNode = void 0,
backNextTreeNode = void 0;
var backNextPosArr = [],
backNextTreeNodeArr = [],
tempBackNextPosArr = [];
//是否为展开的节点,如果展开获取第一个子节点的信息,如果没有取相邻节点,若也没有相邻节点则获取父节点的下一个节点
if (state.expandedKeys.indexOf(treeNode.props.eventKey) > -1) {
nextPos = currentPos + '-0';
} else {
nextPos = currentPos.substr(0, currentPos.lastIndexOf('-') + 1) + nextIndex;
}
//若向下的节点没有了,找到父级相邻节点
var tempPosArr = currentPos.split('-');
var tempPosArrLength = tempPosArr.length;
//将可能是下一个节点的的位置都备份一遍
while (tempPosArrLength > 1) {
backNextPos = tempPosArrLength > 1 && tempPosArr.slice(0, tempPosArrLength - 1).join('-') + '-' + (parseInt(tempPosArr[tempPosArrLength - 1]) + 1);
tempBackNextPosArr.push(backNextPos);
tempPosArr = tempPosArr.slice(0, tempPosArrLength - 1);
tempPosArrLength = tempPosArr.length;
}
//选中下一个相邻的节点
(0, _util.loopAllChildren)(treeChildren, function (itemNode, index, pos, newKey) {
if (pos == nextPos) {
nextTreeNode = itemNode;
}
tempBackNextPosArr.forEach(function (item) {
if (item && item == pos) {
// backNextTreeNode = item;
backNextTreeNodeArr.push(itemNode);
backNextPosArr.push(pos);
}
});
});
//如果没有下一个节点,则获取父节点的下一个节点
if (!nextTreeNode) {
for (var i = 0; i < backNextTreeNodeArr.length; i++) {
if (backNextTreeNodeArr[i]) {
nextTreeNode = backNextTreeNodeArr[i];
nextPos = backNextPosArr[i];
break;
}
}
}
//查询的下一个节点不为空的话,则选中
if (nextTreeNode) {
var queryInfo = 'a[pos="' + nextPos + '"]';
var parentEle = (0, _util.closest)(e.target, ".u-tree");
var focusEle = parentEle ? parentEle.querySelector(queryInfo) : null;
focusEle && focusEle.focus();
var eventKey = nextTreeNode.props.eventKey || nextTreeNode.key;
this.setState({
focusKey: eventKey
});
if (props.autoSelectWhenFocus) {
this.onSelect(nextTreeNode);
}
} else {
this._setDataTransfer(e);
console.debug('%c[bee-tree] [goDown()] nextTreeNode is null, e ==> ', 'color:blue', e);
}
};
Tree.prototype.goUp = function goUp(currentPos, currentIndex, e, treeNode) {
var props = this.props;
var state = this.state;
if (currentIndex == 0 && currentPos.length === 3) {
this._setDataTransfer(e);
console.debug('%c[bee-tree] [goUp()] return with noting to do because currentIndex == 0 && currentPos.length === 3, e ==> ', 'color:blue', e);
return;
}
// 向上键Up
var preIndex = parseInt(currentIndex) - 1;
var prePos = void 0;
if (preIndex >= 0) {
prePos = currentPos.substr(0, currentPos.lastIndexOf('-') + 1) + preIndex;
} else {
prePos = currentPos.substr(0, currentPos.lastIndexOf('-'));
}
var prevTreeNode = void 0,
preElement = void 0;
var treeNodes = props.children || this.cacheTreeNodes;
//选中上一个相邻的节点
(0, _util.loopAllChildren)(treeNodes, function (item, index, pos, newKey) {
if (pos == prePos) {
prevTreeNode = item;
}
});
//查询的上一个节点不为空的话,则选中
if (prevTreeNode) {
if (preIndex >= 0) {
//如果上面的节点展开则默认选择最后一个子节点
if (state.expandedKeys.indexOf(prevTreeNode.key) > -1) {
var preElementArr = e.target.parentElement.previousElementSibling.querySelectorAll('a');
preElement = preElementArr[preElementArr.length - 1];
prePos = preElement.getAttribute('pos');
(0, _util.loopAllChildren)(props.children, function (item, index, pos, newKey) {
if (pos == prePos) {
prevTreeNode = item;
}
});
} else {
//上一个节点没有展开
preElement = e.target.parentElement.previousElementSibling.querySelector('a');
}
} else {
// 不存在上一个节点时,选中它的父节点
preElement = e.target.parentElement.parentElement.parentElement.querySelector('a');
}
} else {
this._setDataTransfer(e);
console.debug('%c[bee-tree] [goUp()] prevTreeNode is null, e ==> ', 'color:blue', e);
}
if (!preElement) {
this._setDataTransfer(e);
console.debug('%c[bee-tree] [goUp()] preElement is null, e ==> ', 'color:blue', e);
}
preElement && preElement.focus();
var eventKey = prevTreeNode.props.eventKey || prevTreeNode.key;
this.setState({
focusKey: eventKey
});
if (props.autoSelectWhenFocus) {
this.onSelect(prevTreeNode);
}
};
// all keyboard events callbacks run from here at first
Tree.prototype.onKeyDown = function onKeyDown(e, treeNode) {
// e.stopPropagation();
var props = this.props;
var currentPos = treeNode.props.pos;
var selectable = treeNode.props.selectable;
var currentIndex = currentPos.substr(currentPos.lastIndexOf('-') + 1);
//向下键down
if (e.keyCode == _tinperBeeCore.KeyCode.DOWN) {
this.goDown(currentPos, currentIndex, e, treeNode);
} else if (e.keyCode == _tinperBeeCore.KeyCode.UP) {
this.goUp(currentPos, currentIndex, e, treeNode);
} else if (e.keyCode == _tinperBeeCore.KeyCode.LEFT && !treeNode.props.isLeaf) {
// 收起树节点
this.onExpand(treeNode, 'left');
} else if (e.keyCode == _tinperBeeCore.KeyCode.RIGHT && !treeNode.props.isLeaf) {
// 展开树节点
this.onExpand(treeNode, 'right');
} else if (e.keyCode == _tinperBeeCore.KeyCode.SPACE) {
this.onSelect(treeNode);
// 如果是多选tree则进行选中或者反选该节点
props.checkable && this.onCheck(treeNode);
} else if (e.keyCode == _tinperBeeCore.KeyCode.ENTER) {
if (props.onDoubleClick) {
this.onDoubleClick(treeNode);
} else {
selectable && this.onSelect(treeNode);
props.checkable && this.onCheck(treeNode);
}
}
this.props.keyFun && this.props.keyFun(e, treeNode);
// e.preventDefault();
};
Tree.prototype._setDataTransfer = function _setDataTransfer(e) {
e.target._dataTransfer = {
ooo: 'bee-tree',
_cancelBubble: false // 向上层发出不取消冒泡标识表示bee-Tree不处理该事件上层可以处理
};
};
Tree.prototype._focusDom = function _focusDom(selectKeyDomPos, targetDom) {
var queryInfo = 'a[pos="' + selectKeyDomPos + '"]';
var parentEle = (0, _util.closest)(targetDom, ".u-tree");
var focusEle = parentEle ? parentEle.querySelector(queryInfo) : null;
if (document.activeElement !== focusEle) {
focusEle && focusEle.focus();
}
};
/**
* 此方法为了解决树快捷键当有的元素隐藏按tab键也要显示的问题
* @param {*} e
*/
Tree.prototype.onUlFocus = function onUlFocus(e) {
var _this5 = this;
var targetDom = e.target;
// 如果当前tree节点不包括上一个焦点节点会触发此方法
if (this.tree == targetDom && !this.isIn && !this.tree.contains(e.relatedTarget)) {
var _props4 = this.props,
onFocus = _props4.onFocus,
children = _props4.children;
var _state$selectedKeys = this.state.selectedKeys,
selectedKeys = _state$selectedKeys === undefined ? [] : _state$selectedKeys;
var tabIndexKey = selectedKeys[0];
var isExist = false;
var treeNode = children && children.length && children[0];
var eventKey = treeNode && (treeNode.props.eventKey || treeNode.key);
if (this.selectKeyDomExist && tabIndexKey || !tabIndexKey) {
isExist = true;
var queryInfo = 'a[pos="' + this.selectKeyDomPos + '"]';
var parentEle = (0, _util.closest)(e.target, ".u-tree");
var focusEle = parentEle ? parentEle.querySelector(queryInfo) : null;
focusEle && focusEle.focus();
// TAB键选中树后默认聚焦在第一个已选中节点并显示 focus 状态。
this.setState({
focusKey: tabIndexKey || eventKey
});
}
var onFocusRes = onFocus && onFocus(isExist);
if (onFocusRes instanceof Promise) {
onFocusRes.then(function () {
_this5._focusDom(_this5.selectKeyDomPos, targetDom);
});
} else {
this._focusDom(this.selectKeyDomPos, targetDom);
}
}
};
Tree.prototype.onUlMouseEnter = function onUlMouseEnter(e) {
this.isIn = true;
// console.log('onUlMouseEnter----isIn-----',this.isIn);
};
Tree.prototype.onUlMouseLeave = function onUlMouseLeave(e) {
this.isIn = false;
// console.log('onUlMouseLeave----isIn-----',this.isIn);
};
Tree.prototype.getFilterExpandedKeys = function getFilterExpandedKeys(props, expandKeyProp, expandAll) {
var keys = props[expandKeyProp];
if (!expandAll && !props.autoExpandParent) {
return keys || [];
}
var expandedPositionArr = [];
if (props.autoExpandParent) {
(0, _util.loopAllChildren)(props.children, function (item, index, pos, newKey) {
if (keys.indexOf(newKey) > -1) {
expandedPositionArr.push(pos);
}
});
}
var filterExpandedKeys = [];
var removeRoot = this.latestState === false && props.canCloseFreely;
this.latestState = null;
(0, _util.loopAllChildren)(props.children, function (item, index, pos, newKey) {
if (expandAll) {
filterExpandedKeys.push(newKey);
} else if (props.autoExpandParent) {
expandedPositionArr.forEach(function (p) {
if ((p.split('-').length > pos.split('-').length && (0, _util.isInclude)(pos.split('-'), p.split('-')) || pos === p) && filterExpandedKeys.indexOf(newKey) === -1) {
filterExpandedKeys.push(newKey);
}
});
}
});
if (removeRoot && this.latestTreeNode.eventKey && filterExpandedKeys.includes(this.latestTreeNode.eventKey)) {
var index = filterExpandedKeys.indexOf(this.latestTreeNode.eventKey);
filterExpandedKeys.splice(index, 1);
}
return filterExpandedKeys.length ? filterExpandedKeys : keys;
};
Tree.prototype.getDefaultExpandedKeys = function getDefaultExpandedKeys(props, willReceiveProps) {
var expandedKeys = willReceiveProps ? undefined : this.getFilterExpandedKeys(props, 'defaultExpandedKeys', props.defaultExpandedKeys.length ? false : props.defaultExpandAll);
if ('expandedKeys' in props) {
expandedKeys = (props.autoExpandParent ? this.getFilterExpandedKeys(props, 'expandedKeys', false) : props.expandedKeys) || [];
}
return expandedKeys;
};
Tree.prototype.getDefaultCheckedKeys = function getDefaultCheckedKeys(props, willReceiveProps) {
var checkedKeys = willReceiveProps ? undefined : props.defaultCheckedKeys;
if ('checkedKeys' in props) {
checkedKeys = props.checkedKeys || [];
if (props.checkStrictly) {
if (props.checkedKeys.checked) {
checkedKeys = props.checkedKeys.checked;
} else if (!Array.isArray(props.checkedKeys)) {
checkedKeys = [];
}
}
}
return checkedKeys;
};
Tree.prototype.getDefaultSelectedKeys = function getDefaultSelectedKeys(props, willReceiveProps) {
var getKeys = function getKeys(keys) {
if (props.multiple) {
return [].concat(_toConsumableArray(keys));
}
if (keys.length) {
return [keys[0]];
}
return keys;
};
var selectedKeys = willReceiveProps ? undefined : getKeys(props.defaultSelectedKeys);
if ('selectedKeys' in props) {
selectedKeys = getKeys(props.selectedKeys);
}
return selectedKeys;
};
Tree.prototype.getRawExpandedKeys = function getRawExpandedKeys() {
if (!this._rawExpandedKeys && 'expandedKeys' in this.props) {
this._rawExpandedKeys = [].concat(_toConsumableArray(this.state.expandedKeys));
}
};
Tree.prototype.getOpenTransitionName = function getOpenTransitionName() {
var props = this.props;
var transitionName = props.openTransitionName;
var animationName = props.openAnimation;
if (!transitionName && typeof animationName === 'string') {
transitionName = props.prefixCls + '-open-' + animationName;
}
return transitionName;
};
Tree.prototype.getDragNodes = function getDragNodes(treeNode) {
var dragNodesKeys = [];
var tPArr = treeNode.props.pos.split('-');
(0, _util.loopAllChildren)(this.props.children, function (item, index, pos, newKey) {
var pArr = pos.split('-');
if (treeNode.props.pos === pos || tPArr.length < pArr.length && (0, _util.isInclude)(tPArr, pArr)) {
dragNodesKeys.push(newKey);
}
});
return dragNodesKeys;
};
Tree.prototype.getExpandedKeys = function getExpandedKeys(treeNode, expand) {
var key = treeNode.props.eventKey;
var expandedKeys = this.state.expandedKeys;
var expandedIndex = expandedKeys.indexOf(key);
var exKeys = void 0;
if (expandedIndex > -1 && !expand) {
exKeys = [].concat(_toConsumableArray(expandedKeys));
exKeys.splice(expandedIndex, 1);
return exKeys;
}
if (expand && expandedKeys.indexOf(key) === -1) {
return expandedKeys.concat([key]);
}
};
Tree.prototype.filterTreeNode = function filterTreeNode(treeNode) {
var filterTreeNode = this.props.filterTreeNode;
if (typeof filterTreeNode !== 'function' || treeNode.props.disabled) {
return false;
}
return filterTreeNode.call(this, treeNode);
};
/**
* 将截取后的 List 数组转换为 Tree 结构,并更新 state
*/
/**
* 深度遍历 treeData把Tree数据拍平变为一维数组
* @param {*} treeData
* @param {*} parentKey 标识父节点
* @param {*} isShown 该节点是否显示在页面中,当节点的父节点是展开状态 或 该节点是根节点时,该值为 true
*/
/**
* 根据 treeData 渲染树节点
* @param data 树形结构的数组
* @param preHeight 前置占位高度
* @param sufHeight 后置占位高度
*/
/**
* @description 计算懒加载时的前置占位和后置占位
* @param start {Number} 开始截取数据的位置
* @param end {Number} 结束截取数据的位置
* @return sumHeight {Number} 空白占位的高度
*/
Tree.prototype.renderTreeNode = function renderTreeNode(child, index) {
var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
// fix: 懒加载场景index 计算错误
var actualIndex = index + parseInt(this.startIndex);
var pos = level + '-' + actualIndex;
var key = child.key || pos;
var state = this.state;
var props = this.props;
var _state$selectedKeys2 = this.state.selectedKeys,
selectedKeys = _state$selectedKeys2 === undefined ? [] : _state$selectedKeys2;
var tabIndexKey = selectedKeys[0];
if (tabIndexKey && key == tabIndexKey) {
this.selectKeyDomExist = true;
this.selectKeyDomPos = pos;
}
// prefer to child's own selectable property if passed
var selectable = props.selectable;
if (child.props.hasOwnProperty('selectable')) {
selectable = child.props.selectable;
}
var draggable = props.draggable;
if (child.props.hasOwnProperty('draggable')) {
draggable = child.props.draggable;
}
var isLeaf = null;
if (child.props.hasOwnProperty('isLeaf')) {
isLeaf = child.props.isLeaf;
}
var cloneProps = {
root: this,
eventKey: key,
pos: pos,
selectable: selectable,
loadData: props.loadData,
onMouseEnter: props.onMouseEnter,
onMouseLeave: props.onMouseLeave,
onRightClick: props.onRightClick,
onDoubleClick: props.onDoubleClick,
onKeyDown: props.onKeyDown,
prefixCls: props.prefixCls,
showLine: props.showLine,
showIcon: props.showIcon,
draggable: draggable,
dragOver: state.dragOverNodeKey === key && this.dropPosition === 0,
dragOverGapTop: state.dragOverNodeKey === key && this.dropPosition === -1,
dragOverGapBottom: state.dragOverNodeKey === key && this.dropPosition === 1,
_dropTrigger: this._dropTrigger,
expanded: state.expandedKeys.indexOf(key) !== -1,
selected: state.selectedKeys.indexOf(key) !== -1,
focused: state.focusKey === key,
openTransitionName: this.getOpenTransitionName(),
openAnimation: props.openAnimation,
filterTreeNode: this.filterTreeNode.bind(this),
openIcon: props.openIcon,
closeIcon: props.closeIcon,
focusable: props.focusable,
tabIndexKey: state.selectedKeys[0],
tabIndexValue: props.tabIndexValue,
ext: child.props.ext,
mustExpandable: props.mustExpandable,
isLeaf: isLeaf
};
if (props.checkable) {
cloneProps.checkable = props.checkable;
if (props.checkStrictly) {
if (state.checkedKeys) {
cloneProps.checked = state.checkedKeys.indexOf(key) !== -1 || false;
}
if (props.checkedKeys && props.checkedKeys.halfChecked) {
cloneProps.halfChecked = props.checkedKeys.halfChecked.indexOf(key) !== -1 || false;
} else {
cloneProps.halfChecked = false;
}
} else {
if (this.checkedKeys) {
cloneProps.checked = this.checkedKeys.indexOf(key) !== -1 || false;
}
cloneProps.halfChecked = this.halfCheckedKeys.indexOf(key) !== -1;
}
}
if (this.treeNodesStates && this.treeNodesStates[pos]) {
_extends(cloneProps, this.treeNodesStates[pos].siblingPosition);
}
return _react2['default'].cloneElement(child, cloneProps);
};
Tree.prototype.render = function render() {
var _this6 = this;
var props = this.props;
var _props5 = this.props,
showLine = _props5.showLine,
prefixCls = _props5.prefixCls,
className = _props5.className,
focusable = _props5.focusable,
checkable = _props5.checkable,
loadData = _props5.loadData,
checkStrictly = _props5.checkStrictly,
tabIndexValue = _props5.tabIndexValue,
lazyLoad = _props5.lazyLoad,
getScrollContainer = _props5.getScrollContainer,
defaultExpandedKeys = _props5.defaultExpandedKeys,
defaultSelectedKeys = _props5.defaultSelectedKeys,
defaultCheckedKeys = _props5.defaultCheckedKeys,
openAnimation = _props5.openAnimation,
draggable = _props5.draggable,
debounceDuration = _props5.debounceDuration,
others = _objectWithoutProperties(_props5, ['showLine', 'prefixCls', 'className', 'focusable', 'checkable', 'loadData', 'checkStrictly', 'tabIndexValue', 'lazyLoad', 'getScrollContainer', 'defaultExpandedKeys', 'defaultSelectedKeys', 'defaultCheckedKeys', 'openAnimation', 'draggable', 'debounceDuration']);
var customProps = _extends({}, (0, _omit2['default'])(others, ['showIcon', 'cancelUnSelect', 'onCheck', 'selectable', 'autoExpandParent', 'defaultExpandAll', 'onExpand', 'autoSelectWhenFocus', 'expandWhenDoubleClick', 'expandedKeys', 'keyFun', 'openIcon', 'closeIcon', 'treeData', 'checkedKeys', 'selectedKeys', 'renderTreeNodes', 'mustExpandable', 'onMouseEnter', 'onMouseLeave', 'onFocus', 'onDoubleClick']));
var _state = this.state,
treeData = _state.treeData,
flatTreeData = _state.flatTreeData;
var startIndex = this.startIndex,
endIndex = this.endIndex,
preHeight = 0,
sufHeight = 0,
treeNode = [],
treeChildren = props.children; //最终渲染在 Tree 标签中的子节点
if (lazyLoad) {
preHeight = this.getSumHeight(0, startIndex);
sufHeight = this.getSumHeight(endIndex, flatTreeData.length);
}
if (!props.children && treeData) {
//传入json数据
treeNode = this.renderTreefromData(treeData);
this.cacheTreeNodes = treeNode;
treeChildren = treeNode;
}
var showLineCls = "";
if (showLine) {
showLineCls = prefixCls + '-show-line';
}
var domProps = {
className: (0, _classnames2['default'])(className, prefixCls, showLineCls),
role: 'tree-node'
};
if (focusable) {
domProps.onFocus = this.onUlFocus;
domProps.onMouseEnter = this.onUlMouseEnter;
domProps.onMouseLeave = this.onUlMouseLeave;
}
// if (props.focusable) {
// // domProps.tabIndex = '0';//需求改成了默认选择第一个节点或者选中的节点
// // domProps.onKeyDown = this.onKeyDown;//添加到具体的treeNode上了
// }
var getTreeNodesStates = function getTreeNodesStates() {
_this6.treeNodesStates = {};
(0, _util.loopAllChildren)(treeChildren, function (item, index, pos, keyOrPos, siblingPosition) {
_this6.treeNodesStates[pos] = {
siblingPosition: siblingPosition
};
}, undefined, startIndex);
};
if (showLine && !checkable) {
getTreeNodesStates();
}
if (checkable && (this.checkedKeysChange || loadData || this.dataChange)) {
if (checkStrictly) {
getTreeNodesStates();
} else if (props._treeNodesStates) {
this.treeNodesStates = props._treeNodesStates.treeNodesStates;
this.halfCheckedKeys = props._treeNodesStates.halfCheckedKeys;
this.checkedKeys = props._treeNodesStates.checkedKeys;
} else {
var checkedKeys = this.state.checkedKeys;
var checkKeys = void 0;
if (!loadData && this.checkKeys && this._checkedKeys && (0, _util.arraysEqual)(this._checkedKeys, checkedKeys) && !this.dataChange) {
// if checkedKeys the same as _checkedKeys from onCheck, use _checkedKeys.
checkKeys = this.checkKeys;
} else {
var checkedPositions = [];
this.treeNodesStates = {};
(0, _util.loopAllChildren)(treeChildren, function (item, index, pos, keyOrPos, siblingPosition) {
_this6.treeNodesStates[pos] = {
node: item,
key: keyOrPos,
checked: false,
halfChecked: false,
siblingPosition: siblingPosition
};
if (checkedKeys.indexOf(keyOrPos) !== -1) {
_this6.treeNodesStates[pos].checked = true;
checkedPositions.push(pos);
}
}, undefined, startIndex);
// if the parent node's key exists, it all children node will be checked
(0, _util.handleCheckState)(this.treeNodesStates, (0, _util.filterParentPosition)(checkedPositions), true);
checkKeys = (0, _util.getCheck)(this.treeNodesStates);
}
this.halfCheckedKeys = checkKeys.halfCheckedKeys;
this.checkedKeys = checkKeys.checkedKeys;
}
}
this.selectKeyDomExist = false;
return lazyLoad ? _react2['default'].createElement(
_infiniteScroll2['default'],
{
className: 'u-tree-infinite-scroll',
treeList: flatTreeData,
debounceDuration: debounceDuration || 150,
handleTreeListChange: this.handleTreeListChange,
getScrollParent: getScrollContainer,
store: this.store
},
_react2['default'].createElement(
'ul',
_extends({}, domProps, { unselectable: 'true', ref: function ref(el) {
_this6.tree = el;
}, tabIndex: focusable && tabIndexValue }, customProps),
_react2['default'].createElement('li', { style: { height: preHeight }, className: 'u-treenode-start', key: 'tree_node_start' }),
_react2['default'].Children.map(treeChildren, this.renderTreeNode, this),
_react2['default'].createElement('li', { style: { height: sufHeight }, className: 'u-treenode-end', key: 'tree_node_end' })
)
) : _react2['default'].createElement(
'ul',
_extends({}, domProps, { unselectable: 'true', ref: function ref(el) {
_this6.tree = el;
}, tabIndex: focusable && tabIndexValue }, customProps),
_react2['default'].Children.map(treeChildren, this.renderTreeNode, this)
);
};
return Tree;
}(_react2['default'].Component);
var _initialiseProps = function _initialiseProps() {
var _this7 = this;
this.hasTreeNode = function () {
var _props6 = _this7.props,
children = _props6.children,
treeData = _props6.treeData;
var noTreeNode = children === null || typeof children === 'undefined' || (typeof children === 'undefined' ? 'undefined' : _typeof(children)) === 'object' && children.length === 0 || (typeof treeData === 'undefined' ? 'undefined' : _typeof(treeData)) === 'object' && treeData.length === 0;
return !noTreeNode;
};
this.calculateRowHeight = function () {
var lazyLoad = _this7.props.lazyLoad;
// 启用懒加载,计算树节点真实高度
if (!lazyLoad) return;
var treenodes = _this7.tree.querySelectorAll('.u-tree-treenode-close')[0];
if (!treenodes) return;
_this7.hasCalculateRowHeight = true;
var rowHeight = treenodes.getBoundingClientRect().height;
_this7.store.setState({
rowHeight: rowHeight
});
};
this.handleTreeListChange = function (treeList, startIndex, endIndex) {
// 属性配置设置
var attr = {
id: 'key',
parendId: 'parentKey',
name: 'title',
rootId: null,
isLeaf: 'isLeaf'
};
var treeData = (0, _util.convertListToTree)(treeList, attr, _this7.flatTreeKeysMap);
_this7.startIndex = typeof startIndex !== "undefined" ? startIndex : _this7.startIndex;
_this7.endIndex = typeof endIndex !== "undefined" ? endIndex : _this7.endIndex;
_this7.setState({
treeData: treeData
});
_this7.dataChange = true;
};
this.deepTraversal = function (treeData) {
var parentKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var isShown = arguments[2];
var expandedKeys = _this7.state.expandedKeys,
expandedKeysSet = _this7.cacheExpandedKeys ? _this7.cacheExpandedKeys : new Set(expandedKeys),
flatTreeData = [],
flatTreeKeysMap = _this7.flatTreeKeysMap,
dataCopy = treeData;
if (Array.isArray(dataCopy)) {
for (var i = 0, l = dataCopy.length; i < l; i++) {
var _dataCopy$i = dataCopy[i],
key = _dataCopy$i.key,
title = _dataCopy$i.title,
children = _dataCopy$i.children,
props = _objectWithoutProperties(_dataCopy$i, ['key', 'title', 'children']),
dataCopyI = new Object(),
isLeaf = children ? false : true;
//如果父节点是收起状态,则子节点的展开状态无意义。(一级节点或根节点直接判断自身状态即可)
var isExpanded = parentKey === null || expandedKeysSet.has(parentKey) ? expandedKeysSet.has(key) : false;
dataCopyI = _extends(dataCopyI, {
key: key,
title: title,
isExpanded: isExpanded,
parentKey: parentKey || null,
isShown: isShown,
isLeaf: isLeaf
}, _extends({}, props));
//该节点的父节点是展开状态 或 该节点是根节点
if (isShown || parentKey === null) {
flatTreeData.push(dataCopyI); // 取每项数据放入一个新数组
flatTreeKeysMap[key] = dataCopyI;
}
if (Array.isArray(children) && children.length > 0) {
// 若存在children则递归调用把数据拼接到新数组中并且删除该children
flatTreeData = flatTreeData.concat(_this7.deepTraversal(children, key, isExpanded));
}
}
}
return flatTreeData;
};
this.renderTreefromData = function (data) {
var _props7 = _this7.props,
renderTitle = _props7.renderTitle,
renderTreeNodes = _props7.renderTreeNodes;
if (renderTreeNodes) {
return renderTreeNodes(data);
}
var loop = function loop(data) {
return data.map(function (item) {
var key = item.key,
title = item.title,
children = item.children,
isLeaf = item.isLeaf,
others = _objectWithoutProperties(item, ['key', 'title', 'children', 'isLeaf']);
if (item.children) {
return _react2['default'].createElement(
_TreeNode2['default'],
_extends({}, others, { key: key, title: renderTitle ? renderTitle(item) : key, isLeaf: isLeaf }),
loop(item.children)
);
}
return _react2['default'].createElement(_TreeNode2['default'], _extends({}, others, { key: key, title: renderTitle ? renderTitle(item) : key, isLeaf: true }));
});
};
return loop(data);
};
this.getSumHeight = function (start, end) {
var sumHeight = 0;
if (start > end) {
return sumHeight;
}
var span = Math.abs(end - start);
if (span) {
sumHeight = span * _this7.store.getState().rowHeight;
}
return sumHeight;
};
};
Tree.propTypes = {
prefixCls: _propTypes2['default'].string,
children: _propTypes2['default'].any,
showLine: _propTypes2['default'].bool,
showIcon: _propTypes2['default'].bool,
selectable: _propTypes2['default'].bool,
multiple: _propTypes2['default'].bool,
checkable: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _propTypes2['default'].node]),
_treeNodesStates: _propTypes2['default'].object,
checkStrictly: _propTypes2['default'].bool,
draggable: _propTypes2['default'].bool,
autoExpandParent: _propTypes2['default'].bool,
defaultExpandAll: _propTypes2['default'].bool,
defaultExpandedKeys: _propTypes2['default'].arrayOf(_propTypes2['default'].string),
expandedKeys: _propTypes2['default'].arrayOf(_propTypes2['default'].string),
defaultCheckedKeys: _propTypes2['default'].arrayOf(_propTypes2['default'].string),
checkedKeys: _propTypes2['default'].oneOfType([_propTypes2['default'].arrayOf(_propTypes2['default'].string), _propTypes2['default'].object]),
defaultSelectedKeys: _propTypes2['default'].arrayOf(_propTypes2['default'].string),
selectedKeys: _propTypes2['default'].arrayOf(_propTypes2['default'].string),
onExpand: _propTypes2['default'].func,
onCheck: _propTypes2['default'].func,
onSelect: _propTypes2['default'].func,
loadData: _propTypes2['default'].func,
onMouseEnter: _propTypes2['default'].func,
onMouseLeave: _propTypes2['default'].func,
onRightClick: _propTypes2['default'].func,
onDragStart: _propTypes2['default'].func,
onDragEnter: _propTypes2['default'].func,
onDragOver: _propTypes2['default'].func,
onDragLeave: _propTypes2['default'].func,
onDrop: _propTypes2['default'].func,
onDragEnd: _propTypes2['default'].func,
filterTreeNode: _propTypes2['default'].func,
openTransitionName: _propTypes2['default'].string,
focusable: _propTypes2['default'].bool,
openAnimation: _propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].object]),
lazyLoad: _propTypes2['default'].bool,
treeData: _propTypes2['default'].array,
renderTreeNodes: _propTypes2['default'].func,
autoSelectWhenFocus: _propTypes2['default'].bool,
getScrollContainer: _propTypes2['default'].func,
expandWhenDoubleClick: _propTypes2['default'].bool
};
Tree.defaultProps = {
prefixCls: 'rc-tree',
showLine: false,
showIcon: true,
selectable: true,
multiple: false,
checkable: false,
checkStrictly: false,
draggable: false,
autoExpandParent: true,
defaultExpandAll: false,
defaultExpandedKeys: [],
defaultCheckedKeys: [],
defaultSelectedKeys: [],
onExpand: noop,
onCheck: noop,
onSelect: noop,
onDragStart: noop,
onDragEnter: noop,
onDragOver: noop,
onDragLeave: noop,
onDrop: noop,
onDragEnd: noop,
tabIndexValue: 0,
lazyLoad: false,
autoSelectWhenFocus: false,
getScrollContainer: noop,
expandWhenDoubleClick: false
};
exports['default'] = Tree;
module.exports = exports['default'];
/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
var _beeAnimate = __webpack_require__(69);
var _beeAnimate2 = _interopRequireDefault(_beeAnimate);
var _util = __webpack_require__(299);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _tinperBeeCore = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
var browserUa = typeof window !== 'undefined' ? (0, _util.browser)(window.navigator) : '';
var ieOrEdge = /.*(IE|Edge).+/.test(browserUa);
// const uaArray = browserUa.split(' ');
// const gtIE8 = uaArray.length !== 2 || uaArray[0].indexOf('IE') === -1 || Number(uaArray[1]) > 8;
var defaultTitle = '---';
var TreeNode = function (_React$Component) {
_inherits(TreeNode, _React$Component);
function TreeNode(props) {
_classCallCheck(this, TreeNode);
var _this2 = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this2.getNodeChildren = function () {
var children = _this2.props.children;
var originList = (0, _util.toArray)(children).filter(function (node) {
return node;
});
var targetList = (0, _util.getNodeChildren)(originList);
if (originList.length !== targetList.length) {
(0, _util.warnOnlyTreeNode)();
}
return targetList;
};
['onExpand', 'onCheck', 'onContextMenu', 'onMouseEnter', 'onMouseLeave', 'onDragStart', 'onDragEnter', 'onDragOver', 'onDragLeave', 'onDrop', 'onDragEnd', 'onDoubleClick', 'onKeyDown'].forEach(function (m) {
_this2[m] = _this2[m].bind(_this2);
});
_this2.state = {
dataLoading: false,
dragNodeHighlight: false
};
return _this2;
}
TreeNode.prototype.componentDidMount = function componentDidMount() {
if (!this.props.root._treeNodeInstances) {
this.props.root._treeNodeInstances = [];
}
this.props.root._treeNodeInstances.push(this);
};
// shouldComponentUpdate(nextProps) {
// if (!nextProps.expanded) {
// return false;
// }
// return true;
// }
TreeNode.prototype.onCheck = function onCheck() {
this.props.root.onCheck(this);
};
TreeNode.prototype.onSelect = function onSelect() {
clearTimeout(this.doubleClickFlag);
var _this = this;
if (this.props.onDoubleClick) {
//执行延时
this.doubleClickFlag = setTimeout(function () {
//do function在此处写单击事件要执行的代码
_this.props.root.onSelect(_this);
}, 300);
} else {
_this.props.root.onSelect(_this);
}
};
TreeNode.prototype.onDoubleClick = function onDoubleClick() {
clearTimeout(this.doubleClickFlag);
this.props.root.onDoubleClick(this);
};
TreeNode.prototype.onMouseEnter = function onMouseEnter(e) {
e.preventDefault();
this.props.root.onMouseEnter(e, this);
};
TreeNode.prototype.onMouseLeave = function onMouseLeave(e) {
e.preventDefault();
this.props.root.onMouseLeave(e, this);
};
TreeNode.prototype.onContextMenu = function onContextMenu(e) {
e.preventDefault();
this.props.root.onContextMenu(e, this);
};
TreeNode.prototype.onDragStart = function onDragStart(e) {
// console.log('dragstart', this.props.eventKey, e);
// e.preventDefault();
e.stopPropagation();
this.setState({
dragNodeHighlight: true
});
this.props.root.onDragStart(e, this);
try {
// ie throw error
// firefox-need-it
e.dataTransfer.setData('text/plain', '');
} finally {
// empty
}
};
TreeNode.prototype.onDragEnter = function onDragEnter(e) {
e.preventDefault();
e.stopPropagation();
this.props.root.onDragEnter(e, this);
};
TreeNode.prototype.onDragOver = function onDragOver(e) {
// todo disabled
e.preventDefault();
e.stopPropagation();
this.props.root.onDragOver(e, this);
return false;
};
TreeNode.prototype.onDragLeave = function onDragLeave(e) {
e.stopPropagation();
this.props.root.onDragLeave(e, this);
};
TreeNode.prototype.onDrop = function onDrop(e) {
e.preventDefault();
e.stopPropagation();
this.setState({
dragNodeHighlight: false
});
this.props.root.onDrop(e, this);
};
TreeNode.prototype.onDragEnd = function onDragEnd(e) {
e.stopPropagation();
this.setState({
dragNodeHighlight: false
});
this.props.root.onDragEnd(e, this);
};
TreeNode.prototype.onExpand = function onExpand() {
var _this3 = this;
var callbackPromise = this.props.root.onExpand(this);
if (callbackPromise && (typeof callbackPromise === 'undefined' ? 'undefined' : _typeof(callbackPromise)) === 'object') {
var setLoading = function setLoading(dataLoading) {
_this3.setState({
dataLoading: dataLoading
});
};
setLoading(true);
callbackPromise.then(function () {
setLoading(false);
}, function () {
setLoading(false);
});
}
};
// keyboard event support
TreeNode.prototype.onKeyDown = function onKeyDown(e) {
this.props.root.onKeyDown(e, this);
if (e.keyCode == _tinperBeeCore.KeyCode.SPACE || e.keyCode == _tinperBeeCore.KeyCode.DOWN || e.keyCode == _tinperBeeCore.KeyCode.LEFT || e.keyCode == _tinperBeeCore.KeyCode.RIGHT || e.keyCode == _tinperBeeCore.KeyCode.UP) {
e.preventDefault();
}
};
TreeNode.prototype.renderSwitcher = function renderSwitcher(props, expandedState) {
var stateIcon = void 0;
var prefixCls = props.prefixCls;
var switcherCls = _defineProperty({}, prefixCls + '-switcher', true);
if (!props.showLine) {
switcherCls[prefixCls + '-noline_' + expandedState] = true;
} else if (props.pos === '0-0') {
switcherCls[prefixCls + '-roots_' + expandedState] = true;
} else {
switcherCls[prefixCls + '-center_' + expandedState] = !props.last;
switcherCls[prefixCls + '-bottom_' + expandedState] = props.last;
}
if (expandedState === 'open' && props.openIcon) {
stateIcon = props.openIcon;
switcherCls['icon-none'] = true;
}
if (expandedState === 'close' && props.closeIcon) {
stateIcon = props.closeIcon;
switcherCls['icon-none'] = true;
}
//switcherCls[stateIcon] = stateIcon;
props.switcherClass ? switcherCls['' + props.switcherClass] = true : '';
if (props.disabled && !props.mustExpandable) {
switcherCls[prefixCls + '-switcher-disabled'] = true;
return _react2['default'].createElement(
'span',
{ className: (0, _classnames2['default'])(switcherCls), style: props.switcherStyle },
stateIcon
);
}
return _react2['default'].createElement(
'span',
{ className: (0, _classnames2['default'])(switcherCls), style: props.switcherStyle, onClick: this.onExpand },
stateIcon
);
};
TreeNode.prototype.renderCheckbox = function renderCheckbox(props) {
var prefixCls = props.prefixCls;
var checkboxCls = _defineProperty({}, prefixCls + '-checkbox', true);
if (props.checked) {
checkboxCls[prefixCls + '-checkbox-checked'] = true;
} else if (props.halfChecked) {
checkboxCls[prefixCls + '-checkbox-indeterminate'] = true;
}
var customEle = null;
if (typeof props.checkable !== 'boolean') {
customEle = props.checkable;
}
if (props.disabled || props.disableCheckbox) {
checkboxCls[prefixCls + '-checkbox-disabled'] = true;
return _react2['default'].createElement(
'span',
{ className: (0, _classnames2['default'])(checkboxCls) },
customEle
);
}
return _react2['default'].createElement(
'span',
{
className: (0, _classnames2['default'])(checkboxCls),
onClick: this.onCheck
},
customEle
);
};
TreeNode.prototype.renderChildren = function renderChildren(props) {
var renderFirst = this.renderFirst;
this.renderFirst = 1;
var transitionAppear = true;
if (!renderFirst && props.expanded) {
transitionAppear = false;
}
var children = props.children;
var newChildren = children;
// 确定所有子节点是否是TreeNode
var allTreeNode = false;
if (Array.isArray(children)) {
for (var index = 0; index < children.length; index++) {
var item = children[index];
allTreeNode = item.type.isTreeNode == 1;
if (!allTreeNode) {
//当检查到子节点中有不是 TreeNode 的,则直接结束检查。同时不会渲染所有子节点
break;
}
}
} else if (children && children.type && children.type.isTreeNode == 1) {
allTreeNode = true;
}
// 如果props.children的长度大于0才可以生成子对象
if (allTreeNode && _react2['default'].Children.count(children)) {
var _cls;
var cls = (_cls = {}, _defineProperty(_cls, props.prefixCls + '-child-tree', true), _defineProperty(_cls, props.prefixCls + '-child-tree-open', props.expanded), _cls);
if (props.showLine) {
cls[props.prefixCls + '-line'] = !props.last;
}
var animProps = {};
if (props.openTransitionName) {
animProps.transitionName = props.openTransitionName;
} else if (_typeof(props.openAnimation) === 'object') {
animProps.animation = _extends({}, props.openAnimation);
if (!transitionAppear) {
delete animProps.animation.appear;
}
}
newChildren = _react2['default'].createElement(
_beeAnimate2['default'],
_extends({}, animProps, {
showProp: 'data-expanded',
transitionAppear: transitionAppear,
component: ''
}),
!props.expanded ? null : _react2['default'].createElement(
'ul',
{ className: (0, _classnames2['default'])(cls), 'data-expanded': props.expanded },
_react2['default'].Children.map(children, function (item, index) {
return props.root.renderTreeNode(item, index, props.pos);
}, props.root)
)
);
}
return newChildren;
};
/**
*判断是否为叶子节点isLeaf的优先级>props.children。如果是异步加载是根据isLeaf的值进行判断的
*
* @returns
* @memberof TreeNode
*/
TreeNode.prototype.checkIsLeaf = function checkIsLeaf() {
var _props = this.props,
isLeaf = _props.isLeaf,
loadData = _props.loadData;
var rs = isLeaf;
if (rs === false || rs === true) {
return rs;
} else {
var hasChildren = this.getNodeChildren().length !== 0;
return !loadData && !hasChildren;
}
};
TreeNode.prototype.render = function render() {
var _iconEleCls,
_this4 = this;
var props = this.props;
var prefixCls = props.prefixCls;
var expandedState = props.expanded ? 'open' : 'close';
var iconState = expandedState;
var canRenderSwitcher = true;
var content = props.title;
var newChildren = this.renderChildren(props);
var openIconCls = false,
closeIconCls = false;
//以下变量控制是否鼠标单机双击方法中的变量
var timer = 0;
var delay = 500;
var prevent = false;
// if (!newChildren || newChildren === props.children) {
// // content = newChildren;
// newChildren = null;
// if (!props.loadData || props.isLeaf) {
// canRenderSwitcher = false;
// iconState = 'docu';
// }
// }
if (this.checkIsLeaf()) {
canRenderSwitcher = false;
iconState = 'docu';
}
// For performance, does't render children into dom when `!props.expanded` (move to Animate)
// if (!props.expanded) {
// newChildren = null;
// }
var iconEleCls = (_iconEleCls = {}, _defineProperty(_iconEleCls, prefixCls + '-iconEle', true), _defineProperty(_iconEleCls, prefixCls + '-icon_loading', this.state.dataLoading), _defineProperty(_iconEleCls, prefixCls + '-icon__' + iconState, true), _iconEleCls);
var selectHandle = function selectHandle() {
var titleClass = props.titleClass ? prefixCls + '-title' + ' ' + props.className : prefixCls + '-title';
// const icon = (props.showIcon || props.loadData && this.state.dataLoading) ?
// <span className={classNames(iconEleCls)}></span> : null;
var icon = void 0;
if (props.showIcon && props.icon) {
icon = _react2['default'].createElement(
'span',
{
className: (0, _classnames2['default'])(prefixCls + '-iconEle', prefixCls + '-icon__customize')
},
typeof currentIcon === 'function' ? _react2['default'].createElement(props.icon, _extends({}, _this4.props)) : props.icon
);
} else if (props.showIcon || props.loadData && _this4.state.dataLoading) {
icon = _react2['default'].createElement('span', { className: (0, _classnames2['default'])(iconEleCls) });
}
var title = _react2['default'].createElement(
'span',
{ className: titleClass, style: props.titleStyle },
content
);
var wrap = prefixCls + '-node-content-wrapper';
var domProps = {
className: wrap + ' ' + wrap + '-' + (iconState === expandedState ? iconState : 'normal')
};
if (!props.disabled) {
if (props.selected || !props._dropTrigger && _this4.state.dragNodeHighlight) {
domProps.className += ' ' + prefixCls + '-node-selected';
}
domProps.onClick = function (e) {
var _this = _this4;
e.preventDefault();
if (props.selectable) {
_this.onSelect();
}
// not fire check event
// if (props.checkable) {
// this.onCheck();
// }
};
if (props.onDoubleClick) {
domProps.onDoubleClick = _this4.onDoubleClick;
}
if (props.onRightClick) {
domProps.onContextMenu = _this4.onContextMenu;
}
if (props.onMouseEnter) {
domProps.onMouseEnter = _this4.onMouseEnter;
}
if (props.onMouseLeave) {
domProps.onMouseLeave = _this4.onMouseLeave;
}
if (props.draggable) {
domProps.className += ' draggable';
if (ieOrEdge) {
// ie bug!
domProps.href = '#';
}
domProps.draggable = true;
domProps['aria-grabbed'] = true;
domProps.onDragStart = _this4.onDragStart;
}
}
//设置tabIndex
if (props.focusable) {
domProps.onKeyDown = _this4.onKeyDown;
domProps.tabIndex = -1;
if (props.tabIndexKey) {
if (props.eventKey == props.tabIndexKey) {
domProps.tabIndex = props.tabIndexValue;
}
} else if (props.pos == '0-0') {
domProps.tabIndex = props.tabIndexValue;
}
}
return _react2['default'].createElement(
'a',
_extends({ ref: function ref(el) {
_this4.selectHandle = el;
}, pos: props.pos, title: typeof content === 'string' ? content : '' }, domProps),
icon,
title
);
};
var liProps = {};
if (props.liAttr) {
liProps = _extends({}, props.liAttr);
}
if (props.draggable) {
liProps.onDragEnter = this.onDragEnter;
liProps.onDragOver = this.onDragOver;
liProps.onDragLeave = this.onDragLeave;
liProps.onDrop = this.onDrop;
liProps.onDragEnd = this.onDragEnd;
}
var disabledCls = '';
var dragOverCls = '';
if (props.disabled) {
disabledCls = prefixCls + '-treenode-disabled';
} else if (props.dragOver) {
dragOverCls = 'drag-over';
} else if (props.dragOverGapTop) {
dragOverCls = 'drag-over-gap-top';
} else if (props.dragOverGapBottom) {
dragOverCls = 'drag-over-gap-bottom';
}
var filterCls = props.filterTreeNode ? props.filterTreeNode(this) ? 'filter-node' : '' : '';
var noopSwitcher = function noopSwitcher() {
var _cls2;
var cls = (_cls2 = {}, _defineProperty(_cls2, prefixCls + '-switcher', true), _defineProperty(_cls2, prefixCls + '-switcher-noop', true), _cls2);
if (props.showLine) {
// console.log('line---------');
cls[prefixCls + '-center_docu'] = !props.last;
cls[prefixCls + '-bottom_docu'] = props.last;
} else {
cls[prefixCls + '-noline_docu'] = true;
}
return _react2['default'].createElement('span', { className: (0, _classnames2['default'])(cls) });
};
var selectedCls = props.selected ? prefixCls + '-treenode-selected' : '';
var focusedCls = props.focused ? prefixCls + '-treenode-focused' : '';
var expandedCls = prefixCls + '-treenode-' + expandedState;
return _react2['default'].createElement(
'li',
_extends({}, liProps, { style: props.style,
className: (0, _classnames2['default'])(props.className, disabledCls, dragOverCls, filterCls, selectedCls, focusedCls, expandedCls)
}),
canRenderSwitcher ? this.renderSwitcher(props, expandedState) : noopSwitcher(),
props.checkable ? this.renderCheckbox(props) : null,
selectHandle(),
newChildren
);
};
return TreeNode;
}(_react2['default'].Component);
TreeNode.isTreeNode = 1;
TreeNode.propTypes = {
prefixCls: _propTypes2['default'].string,
disabled: _propTypes2['default'].bool,
disableCheckbox: _propTypes2['default'].bool,
expanded: _propTypes2['default'].bool,
isLeaf: _propTypes2['default'].bool,
root: _propTypes2['default'].object,
onSelect: _propTypes2['default'].func,
openIcon: _propTypes2['default'].element,
closeIcon: _propTypes2['default'].element,
style: _propTypes2['default'].object,
className: _propTypes2['default'].string,
titleClass: _propTypes2['default'].string,
titleStyle: _propTypes2['default'].object,
switcherClass: _propTypes2['default'].string,
switcherStyle: _propTypes2['default'].object
};
TreeNode.defaultProps = {
title: defaultTitle,
tabIndexValue: 0,
mustExpandable: false
};
exports['default'] = TreeNode;
module.exports = exports['default'];
/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.browser = browser;
exports.getOffset = getOffset;
exports.loopAllChildren = loopAllChildren;
exports.isInclude = isInclude;
exports.filterParentPosition = filterParentPosition;
exports.handleCheckState = handleCheckState;
exports.getCheck = getCheck;
exports.getStrictlyValue = getStrictlyValue;
exports.arraysEqual = arraysEqual;
exports.closest = closest;
exports.isTreeNode = isTreeNode;
exports.toArray = toArray;
exports.getNodeChildren = getNodeChildren;
exports.warnOnlyTreeNode = warnOnlyTreeNode;
exports.convertListToTree = convertListToTree;
exports.throttle = throttle;
exports.debounce = debounce;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /* eslint no-loop-func: 0*/
function browser(navigator) {
var tem = void 0;
var ua = navigator.userAgent;
var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE ' + (tem[1] || '');
}
if (M[1] === 'Chrome') {
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if (tem) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
tem = ua.match(/version\/(\d+)/i);
if (tem) {
M.splice(1, 1, tem[1]);
}
return M.join(' ');
}
// export function getOffset(el) {
// const obj = el.getBoundingClientRect();
// return {
// left: obj.left + document.body.scrollLeft,
// top: obj.top + document.body.scrollTop,
// width: obj.width,
// height: obj.height
// };
// }
// // iscroll offset
// offset = function (el) {
// var left = -el.offsetLeft,
// top = -el.offsetTop;
// // jshint -W084
// while (el = el.offsetParent) {
// left -= el.offsetLeft;
// top -= el.offsetTop;
// }
// // jshint +W084
// return {
// left: left,
// top: top
// };
// }
/* eslint-disable */
function getOffset(ele) {
var doc = void 0,
win = void 0,
docElem = void 0,
rect = void 0;
if (!ele.getClientRects().length) {
return { top: 0, left: 0 };
}
rect = ele.getBoundingClientRect();
if (rect.width || rect.height) {
doc = ele.ownerDocument;
win = doc.defaultView;
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
return rect;
}
/* eslint-enable */
function getChildrenlength(children) {
var len = 1;
if (Array.isArray(children)) {
len = children.length;
}
return len;
}
function getSiblingPosition(index, len, siblingPosition) {
if (len === 1) {
siblingPosition.first = true;
siblingPosition.last = true;
} else {
siblingPosition.first = index === 0;
siblingPosition.last = index === len - 1;
}
return siblingPosition;
}
function loopAllChildren(childs, callback, parent) {
var baseNum = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var loop = function loop(children, level, _parent) {
var len = getChildrenlength(children);
_react2['default'].Children.forEach(children, function (item, index) {
var pos = level + '-' + (index + parseInt(baseNum));
if (item.props.children && item.type && item.type.isTreeNode) {
loop(item.props.children, pos, { node: item, pos: pos });
}
callback(item, index, pos, item.key || pos, getSiblingPosition(index, len, {}), _parent);
});
};
loop(childs, 0, parent);
}
function isInclude(smallArray, bigArray) {
return smallArray.every(function (ii, i) {
return ii === bigArray[i];
});
}
// console.log(isInclude(['0', '1'], ['0', '10', '1']));
// arr.length === 628, use time: ~20ms
function filterParentPosition(arr) {
var levelObj = {};
arr.forEach(function (item) {
var posLen = item.split('-').length;
if (!levelObj[posLen]) {
levelObj[posLen] = [];
}
levelObj[posLen].push(item);
});
var levelArr = Object.keys(levelObj).sort();
var _loop = function _loop(i) {
if (levelArr[i + 1]) {
levelObj[levelArr[i]].forEach(function (ii) {
var _loop2 = function _loop2(j) {
levelObj[levelArr[j]].forEach(function (_i, index) {
if (isInclude(ii.split('-'), _i.split('-'))) {
levelObj[levelArr[j]][index] = null;
}
});
levelObj[levelArr[j]] = levelObj[levelArr[j]].filter(function (p) {
return p;
});
};
for (var j = i + 1; j < levelArr.length; j++) {
_loop2(j);
}
});
}
};
for (var i = 0; i < levelArr.length; i++) {
_loop(i);
}
var nArr = [];
levelArr.forEach(function (i) {
nArr = nArr.concat(levelObj[i]);
});
return nArr;
}
// console.log(filterParentPosition(
// ['0-2', '0-3-3', '0-10', '0-10-0', '0-0-1', '0-0', '0-1-1', '0-1']
// ));
function stripTail(str) {
var arr = str.match(/(.+)(-[^-]+)$/);
var st = '';
if (arr && arr.length === 3) {
st = arr[1];
}
return st;
}
function splitPosition(pos) {
return pos.split('-');
}
function handleCheckState(obj, checkedPositionArr, checkIt) {
// console.log(stripTail('0-101-000'));
var objKeys = Object.keys(obj);
// let s = Date.now();
objKeys.forEach(function (i, index) {
var iArr = splitPosition(i);
var saved = false;
checkedPositionArr.forEach(function (_pos) {
// 设置子节点,全选或全不选
var _posArr = splitPosition(_pos);
if (iArr.length > _posArr.length && isInclude(_posArr, iArr)) {
obj[i].halfChecked = false;
obj[i].checked = checkIt;
objKeys[index] = null;
}
if (iArr[0] === _posArr[0] && iArr[1] === _posArr[1]) {
// 如果
saved = true;
}
});
if (!saved) {
objKeys[index] = null;
}
});
// TODO: 循环 2470000 次耗时约 1400 ms。 性能瓶颈!
// console.log(Date.now()-s, checkedPositionArr.length * objKeys.length);
objKeys = objKeys.filter(function (i) {
return i;
}); // filter non null;
var _loop3 = function _loop3(_pIndex) {
// 循环设置父节点的 选中 或 半选状态
var loop = function loop(__pos) {
var _posLen = splitPosition(__pos).length;
if (_posLen <= 2) {
// e.g. '0-0', '0-1'
return;
}
var sibling = 0;
var siblingChecked = 0;
var parentPosition = stripTail(__pos);
objKeys.forEach(function (i /* , index*/) {
var iArr = splitPosition(i);
if (iArr.length === _posLen && isInclude(splitPosition(parentPosition), iArr)) {
sibling++;
if (obj[i].checked) {
siblingChecked++;
var _i = checkedPositionArr.indexOf(i);
if (_i > -1) {
checkedPositionArr.splice(_i, 1);
if (_i <= _pIndex) {
_pIndex--;
}
}
} else if (obj[i].halfChecked) {
siblingChecked += 0.5;
}
// objKeys[index] = null;
}
});
// objKeys = objKeys.filter(i => i); // filter non null;
var parent = obj[parentPosition];
// sibling 不会等于0
// 全不选 - 全选 - 半选
if (siblingChecked === 0) {
parent.checked = false;
parent.halfChecked = false;
} else if (siblingChecked === sibling) {
parent.checked = true;
parent.halfChecked = false;
} else {
parent.halfChecked = true;
parent.checked = false;
}
loop(parentPosition);
};
loop(checkedPositionArr[_pIndex], _pIndex);
pIndex = _pIndex;
};
for (var pIndex = 0; pIndex < checkedPositionArr.length; pIndex++) {
_loop3(pIndex);
}
// console.log(Date.now()-s, objKeys.length, checkIt);
}
function getCheck(treeNodesStates) {
var halfCheckedKeys = [];
var checkedKeys = [];
var checkedNodes = [];
var checkedNodesPositions = [];
Object.keys(treeNodesStates).forEach(function (item) {
var itemObj = treeNodesStates[item];
if (itemObj.checked) {
checkedKeys.push(itemObj.key);
checkedNodes.push(itemObj.node);
checkedNodesPositions.push({ node: itemObj.node, pos: item });
} else if (itemObj.halfChecked) {
halfCheckedKeys.push(itemObj.key);
}
});
return {
halfCheckedKeys: halfCheckedKeys, checkedKeys: checkedKeys, checkedNodes: checkedNodes, checkedNodesPositions: checkedNodesPositions, treeNodesStates: treeNodesStates
};
}
function getStrictlyValue(checkedKeys, halfChecked) {
if (halfChecked) {
return { checked: checkedKeys, halfChecked: halfChecked };
}
return checkedKeys;
}
function arraysEqual(a, b) {
if (a === b) return true;
if (a === null || typeof a === 'undefined' || b === null || typeof b === 'undefined') {
return false;
}
if (a.length !== b.length) return false;
// If you don't care about the order of the elements inside
// the array, you should sort both arrays here.
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
function closest(el, selector) {
var matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
while (el) {
if (matchesSelector.call(el, selector)) {
return el;
} else {
el = el.parentElement;
}
}
return null;
}
function isTreeNode(node) {
return node && node.type && node.type.isTreeNode;
}
function toArray(children) {
var ret = [];
_react2['default'].Children.forEach(children, function (c) {
ret.push(c);
});
return ret;
}
function getNodeChildren(children) {
return toArray(children).filter(isTreeNode);
}
var onlyTreeNodeWarned = false;
function warnOnlyTreeNode() {
if (onlyTreeNodeWarned) return;
onlyTreeNodeWarned = true;
console.warn('Tree only accept TreeNode as children.');
}
/**
* 将一维数组转换为树结构
* @param {*} treeData 扁平结构的 List 数组
* @param {*} attr 属性配置设置
* @param {*} flatTreeKeysMap 存储所有 key-value 的映射,方便获取各节点信息
*/
function convertListToTree(treeData, attr, flatTreeKeysMap) {
var tree = []; //存储所有一级节点
var resData = treeData,
//resData 存储截取的节点 + 父节点(除一级节点外)
resKeysMap = {},
//resData 的Map映射
treeKeysMap = {}; //tree 的Map映射
resData.map(function (element) {
var key = attr.id;
resKeysMap[element[key]] = element;
});
// 查找父节点,为了补充不完整的数据结构
var findParentNode = function findParentNode(node) {
var parentKey = node[attr.parendId];
if (parentKey !== attr.rootId) {
//如果不是根节点,则继续递归
var item = flatTreeKeysMap[parentKey];
// 用 resKeysMap 判断,避免重复计算某节点的父节点
if (resKeysMap.hasOwnProperty(item[attr.id])) return;
resData.unshift(item);
resKeysMap[item[attr.id]] = item;
findParentNode(item);
} else {
// 用 treeKeysMap 判断,避免重复累加
if (!treeKeysMap.hasOwnProperty(node[attr.id])) {
var key = node.key,
title = node.title,
children = node.children,
isLeaf = node.isLeaf,
otherProps = _objectWithoutProperties(node, ['key', 'title', 'children', 'isLeaf']);
var obj = {
key: key,
title: title,
isLeaf: isLeaf
// children: []
};
if (!obj.isLeaf) {
obj.children = [];
}
tree.push(_extends(obj, _extends({}, otherProps)));
treeKeysMap[key] = node;
}
}
};
// 遍历 resData ,找到所有的一级节点
for (var i = 0; i < resData.length; i++) {
var item = resData[i];
if (item[attr.parendId] === attr.rootId && !treeKeysMap.hasOwnProperty(item[attr.id])) {
//如果是根节点,就存放进 tree 对象中
var key = item.key,
title = item.title,
children = item.children,
otherProps = _objectWithoutProperties(item, ['key', 'title', 'children']);
var obj = {
key: item[attr.id],
title: item[attr.name],
isLeaf: item[attr.isLeaf]
};
if (!obj.isLeaf) {
obj.children = [];
}
tree.push(_extends(obj, _extends({}, otherProps)));
treeKeysMap[key] = item;
resData.splice(i, 1);
i--;
} else {
//递归查找根节点信息
findParentNode(item);
}
}
// console.log('resData',resKeysMap);
var run = function run() {
var treeArrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
if (resData.length > 0) {
for (var _i2 = 0; _i2 < treeArrs.length; _i2++) {
for (var j = 0; j < resData.length; j++) {
var _item = resData[j];
if (treeArrs[_i2].key === _item[attr.parendId]) {
var _key = _item.key,
_title = _item.title,
_children = _item.children,
_otherProps = _objectWithoutProperties(_item, ['key', 'title', 'children']);
var _obj = {
key: _item[attr.id],
title: _item[attr.name],
isLeaf: _item[attr.isLeaf]
// children: []
};
if (!_obj.isLeaf) {
_obj.children = [];
}
treeArrs[_i2].children.push(_extends(_obj, _extends({}, _otherProps)));
resData.splice(j, 1);
j--;
}
}
run(treeArrs[_i2].children);
}
}
};
run(tree);
return tree;
}
function isObject(value) {
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
return value != null && (type == 'object' || type == 'function');
}
/**
* 函数节流
* @param {*} func 延时调用函数
* @param {*} wait 延迟多长时间
* @return Function 延迟执行的方法
*/
function throttle(fn, wait) {
var last = void 0;
return function () {
var now = Date.now();
if (!last) {
fn.apply(this, arguments);
last = now;
return;
}
if (now - last >= wait) {
fn.apply(this, arguments);
last = now;
}
};
}
/**
* 函数防抖
* @param {*} func 延时调用函数
* @param {*} wait 延迟多长时间
* @return Function 延迟执行的方法
*/
function debounce(fn, delay) {
var timeout = null; // 创建一个标记用来存放定时器的返回值
return function (e) {
var _this = this,
_arguments = arguments;
// 每当用户输入的时候把前一个 setTimeout clear 掉
clearTimeout(timeout);
// 然后又创建一个新的 setTimeout, 这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
timeout = setTimeout(function () {
fn.apply(_this, _arguments);
}, delay);
};
}
/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(6);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _util = __webpack_require__(299);
var _config = __webpack_require__(301);
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
* 处理滚动加载逻辑
*/
var InfiniteScroll = function (_Component) {
_inherits(InfiniteScroll, _Component);
function InfiniteScroll(props) {
_classCallCheck(this, InfiniteScroll);
//默认显示20条rowsInView根据定高算的。在非固定高下这个只是一个大概的值。
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.eventListenerOptions = function () {
var options = _this.props.useCapture;
if (_this.isPassiveSupported()) {
options = {
useCapture: _this.props.useCapture,
passive: true
};
}
return options;
};
_this.mousewheelListener = function (e) {
// Prevents Chrome hangups
// See: https://stackoverflow.com/questions/47524205/random-high-content-download-time-in-chrome/47684257#47684257
if (e.deltaY === 1 && !_this.isPassiveSupported()) {
e.preventDefault();
}
};
_this.scrollListener = function () {
var el = _this.scrollComponent;
var parentNode = _this.getParentElement(el);
_this.scrollTop = parentNode.scrollTop;
_this.handleScrollY();
};
_this.handleScrollY = function (isNewDataLess) {
var store = _this.props.store;
var parentElement = _this.getParentElement(_this.scrollComponent);
if (!parentElement) {
return;
}
var scrollEl = parentElement;
var scrollY = scrollEl && scrollEl.clientHeight;
var rowHeight = store.getState().rowHeight;
//默认显示20条rowsInView根据定高算的。在非固定高下这个只是一个大概的值。
_this.rowsInView = scrollY ? Math.floor(scrollY / rowHeight) : _config2['default'].defaultRowsInView;
var currentIndex = _this.currentIndex,
startIndex = _this.startIndex,
endIndex = _this.endIndex,
treeList = _this.treeList,
loadCount = _this.loadCount,
rowsInView = _this.rowsInView;
var index = 0;
var tempScrollTop = _this.scrollTop;
//根据 scrollTop 计算 currentIndex
while (tempScrollTop > 0) {
tempScrollTop -= rowHeight;
if (tempScrollTop > 0) {
index += 1;
}
}
if (isNewDataLess) {
parentElement.scrollTop = 0;
}
//true 为向下滚动, false 为向上滚动
var isScrollDown = index - currentIndex > 0 ? true : false;
if (index < 0) index = 0;
//如果之前的索引和下一次的不一样则重置索引和滚动的位置
_this.currentIndex = currentIndex !== index ? index : currentIndex;
// 如果rowsInView 小于 缓存的数据则重新render
// 向下滚动 下临界值超出缓存的endIndex则重新渲染
if (isScrollDown && rowsInView + index > endIndex - _config2['default'].rowDiff) {
startIndex = index - _config2['default'].loadBuffer > 0 ? index - _config2['default'].loadBuffer : 0;
endIndex = startIndex + loadCount;
if (endIndex > treeList.length) {
endIndex = treeList.length;
}
if (endIndex > _this.endIndex) {
_this.startIndex = startIndex;
_this.endIndex = endIndex;
_this.sliceTreeList(_this.startIndex, _this.endIndex);
}
}
// 向上滚动当前的index是否已经加载currentIndex若干上临界值小于startIndex则重新渲染
if (!isScrollDown && index < startIndex + _config2['default'].rowDiff) {
startIndex = index - _config2['default'].loadBuffer;
if (startIndex < 0) {
startIndex = 0;
}
if (startIndex <= _this.startIndex) {
_this.startIndex = startIndex;
_this.endIndex = _this.startIndex + loadCount;
_this.sliceTreeList(_this.startIndex, _this.endIndex);
}
}
};
_this.sliceTreeList = function (startIndex, endIndex) {
var newTreeList = []; //存储截取后的新数据
newTreeList = _this.treeList.slice(startIndex, endIndex);
_this.props.handleTreeListChange && _this.props.handleTreeListChange(newTreeList, startIndex, endIndex);
};
_this.rowsInView = _config2['default'].defaultRowsInView;
//一维数组
_this.treeList = props.treeList;
//一次加载多少数据
_this.loadCount = _config2['default'].loadBuffer ? _this.rowsInView + _config2['default'].loadBuffer * 2 : 16;
//可视区第一条数据的 index
_this.currentIndex = 0;
_this.startIndex = _this.currentIndex; //数据开始位置
_this.endIndex = _this.currentIndex + _this.loadCount; //数据结束位置
return _this;
}
InfiniteScroll.prototype.componentDidMount = function componentDidMount() {
this.options = this.eventListenerOptions();
this.attachScrollListener();
};
InfiniteScroll.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var newTreeList = nextProps.treeList;
var oldTreeList = this.props.treeList;
if (newTreeList !== oldTreeList) {
var isNewDataLess = newTreeList.length < oldTreeList.length;
this.treeList = newTreeList;
this.handleScrollY(isNewDataLess);
}
};
// componentDidUpdate() {
// const el = this.scrollComponent;
// const parentNode = this.getParentElement(el);
// parentNode.scrollTop = this.scrollTop;
// };
InfiniteScroll.prototype.componentWillUnmount = function componentWillUnmount() {
this.detachScrollListener();
this.detachMousewheelListener();
};
InfiniteScroll.prototype.isPassiveSupported = function isPassiveSupported() {
var passive = false;
var testOptions = {
get passive() {
passive = true;
}
};
try {
document.addEventListener('test', null, testOptions);
document.removeEventListener('test', null, testOptions);
} catch (e) {
// ignore
}
return passive;
};
/**
* 解除mousewheel事件监听
*/
InfiniteScroll.prototype.detachMousewheelListener = function detachMousewheelListener() {
var scrollEl = window;
if (this.props.useWindow === false) {
scrollEl = this.scrollComponent.parentNode;
}
scrollEl.removeEventListener('mousewheel', this.mousewheelListener, this.options ? this.options : this.props.useCapture);
};
/**
* 解除scroll事件监听
*/
InfiniteScroll.prototype.detachScrollListener = function detachScrollListener() {
var scrollEl = window;
if (this.props.useWindow === false) {
scrollEl = this.getParentElement(this.scrollComponent);
}
scrollEl.removeEventListener('scroll', this.scrollListener, this.options ? this.options : this.props.useCapture);
scrollEl.removeEventListener('resize', this.scrollListener, this.options ? this.options : this.props.useCapture);
};
/**
* 获取父组件(用户自定义父组件或者当前dom的parentNode)
* @param {*} el
*/
InfiniteScroll.prototype.getParentElement = function getParentElement(el) {
var scrollParent = this.props.getScrollParent && this.props.getScrollParent();
if (scrollParent != null) {
return scrollParent;
}
return el && el.parentNode;
};
InfiniteScroll.prototype.filterProps = function filterProps(props) {
return props;
};
/**
* 绑定scroll事件
*/
InfiniteScroll.prototype.attachScrollListener = function attachScrollListener() {
var _props = this.props,
store = _props.store,
debounceDuration = _props.debounceDuration;
var parentElement = this.getParentElement(this.scrollComponent);
if (!parentElement) {
return;
}
var scrollEl = parentElement;
var scrollY = scrollEl && scrollEl.clientHeight;
var rowHeight = store.getState().rowHeight;
//默认显示20条rowsInView根据定高算的。
this.rowsInView = scrollY ? Math.floor(scrollY / rowHeight) : _config2['default'].defaultRowsInView;
scrollEl.addEventListener('scroll', (0, _util.throttle)(this.scrollListener, debounceDuration || 150), this.options ? this.options : this.props.useCapture);
scrollEl.addEventListener('resize', (0, _util.throttle)(this.scrollListener, debounceDuration || 150), this.options ? this.options : this.props.useCapture);
};
/**
* 滚动事件监听
*/
/**
* @description 根据返回的scrollTop计算当前的索引。
*/
/**
* 根据 startIndex 和 endIndex 截取数据
* @param startIndex
* @param endIndex
*/
InfiniteScroll.prototype.render = function render() {
var _this2 = this;
var _props2 = this.props,
children = _props2.children,
element = _props2.element,
ref = _props2.ref,
getScrollParent = _props2.getScrollParent,
treeList = _props2.treeList,
handleTreeListChange = _props2.handleTreeListChange,
store = _props2.store,
props = _objectWithoutProperties(_props2, ['children', 'element', 'ref', 'getScrollParent', 'treeList', 'handleTreeListChange', 'store']);
props.ref = function (node) {
_this2.scrollComponent = node;
if (ref) {
ref(node);
}
};
var childrenArray = [children];
return _react2['default'].createElement(element, props, childrenArray);
};
return InfiniteScroll;
}(_react.Component);
InfiniteScroll.propTypes = {
children: _propTypes2['default'].node.isRequired,
element: _propTypes2['default'].node,
ref: _propTypes2['default'].func,
getScrollParent: _propTypes2['default'].func,
treeList: _propTypes2['default'].array,
handleTreeListChange: _propTypes2['default'].func
};
InfiniteScroll.defaultProps = {
element: 'div',
ref: null,
getScrollParent: null,
treeList: [],
handleTreeListChange: function handleTreeListChange() {}
};
exports['default'] = InfiniteScroll;
module.exports = exports['default'];
/***/ }),
/* 301 */
/***/ (function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* 在此存储全局配置项
*/
// 树懒加载功能,需要用到的变量
exports["default"] = {
loadBuffer: 20, //懒加载时缓冲区数据量
defaultRowsInView: 20, //可视区数据量
rowDiff: 10 //行差值,需要重新截取数据的阈值
};
module.exports = exports["default"];
/***/ }),
/* 302 */
/***/ (function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports["default"] = createStore;
function createStore(initialState) {
var state = initialState;
var listeners = [];
function setState(partial) {
state = _extends({}, state, partial);
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
}
function getState() {
return state;
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
var index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
setState: setState,
getState: getState,
subscribe: subscribe
};
}
module.exports = exports["default"];
/***/ }),
/* 303 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _tinperBeeCore = __webpack_require__(27);
function animate(node, show, done) {
var height = void 0;
return (0, _tinperBeeCore.cssAnimation)(node, 'u-motion-collapse', {
start: function start() {
if (!show) {
node.style.height = node.offsetHeight + 'px';
} else {
height = node.offsetHeight;
node.style.height = 0;
}
},
active: function active() {
node.style.height = (show ? height : 0) + 'px';
},
end: function end() {
node.style.height = '';
done();
}
});
}
var animation = {
enter: function enter(node, done) {
return animate(node, true, done);
},
leave: function leave(node, done) {
return animate(node, false, done);
},
appear: function appear(node, done) {
return animate(node, true, done);
}
};
exports['default'] = animation;
module.exports = exports['default'];
/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
var _beeIcon = __webpack_require__(79);
var _beeIcon2 = _interopRequireDefault(_beeIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree基本使用示例
* @description 示例涵盖 checkbox如何选择disable状态和部分选择状态。checkStrictly为true时子节点与父节点的选择情况都不会影响到对方
*
*/
var TreeNode = _src2['default'].TreeNode;
var defaultProps = {
keys: ['0-0-0', '0-0-1']
};
var Demo1 = function (_Component) {
_inherits(Demo1, _Component);
function Demo1(props) {
_classCallCheck(this, Demo1);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onCheck = function (checkedKeys, newst) {
//用户可以自定义当前选中和半选中的节点。
console.log('onCheck', checkedKeys);
var cks = {
checked: checkedKeys.checked || checkedKeys,
halfChecked: checkedKeys.halfChecked
};
_this.setState({ checkedKeys: cks });
};
_this.onDoubleClick = function (key, treeNode) {
console.log('---onDblClick---', key, '--treeNode--', treeNode);
};
var keys = _this.props.keys;
_this.state = {
defaultExpandedKeys: keys,
defaultSelectedKeys: keys,
defaultCheckedKeys: keys,
checkedKeys: { checked: keys }
};
return _this;
}
Demo1.prototype.onSelect = function onSelect(info) {
console.log('selected', info);
};
Demo1.prototype.render = function render() {
return _react2['default'].createElement(
_src2['default'],
{
className: 'myCls',
showLine: true,
checkable: true,
defaultExpandedKeys: this.state.defaultExpandedKeys,
defaultSelectedKeys: this.state.defaultSelectedKeys,
defaultCheckedKeys: this.state.defaultCheckedKeys,
checkStrictly: true,
showIcon: true,
cancelUnSelect: true,
onSelect: this.onSelect,
onCheck: this.onCheck,
onDoubleClick: this.onDoubleClick
},
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1', key: '0-0', icon: _react2['default'].createElement(_beeIcon2['default'], { type: 'uf-treefolder' }) },
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-0', key: '0-0-0', disabled: true, icon: _react2['default'].createElement(_beeIcon2['default'], { type: 'uf-treefolder' }) },
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-0-0', disableCheckbox: true, icon: _react2['default'].createElement(_beeIcon2['default'], { type: 'uf-list-s-o' }) }),
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-0-1', icon: _react2['default'].createElement(_beeIcon2['default'], { type: 'uf-list-s-o' }) })
),
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-1', key: '0-0-1', icon: _react2['default'].createElement(_beeIcon2['default'], { type: 'uf-treefolder' }) },
_react2['default'].createElement(TreeNode, { title: _react2['default'].createElement(
'span',
null,
'sss'
), key: '0-0-1-0', icon: _react2['default'].createElement(_beeIcon2['default'], { type: 'uf-list-s-o' }) })
)
)
);
};
return Demo1;
}(_react.Component);
Demo1.defaultProps = defaultProps;
exports['default'] = Demo1;
module.exports = exports['default'];
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree数据可控示例
* @description
* 
*/
var x = 6;
var y = 5;
var z = 2;
var gData = [];
var generateData = function generateData(_level, _preKey, _tns) {
var preKey = _preKey || '0';
var tns = _tns || gData;
var children = [];
for (var i = 0; i < x; i++) {
var key = preKey + '-' + i;
tns.push({ title: key, key: key });
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
var level = _level - 1;
children.forEach(function (key, index) {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
var TreeNode = _src2['default'].TreeNode;
var Demo2 = function (_Component) {
_inherits(Demo2, _Component);
function Demo2(props) {
_classCallCheck(this, Demo2);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onKeyDown = function (e, treeNode) {
console.log('***', e);
return false;
};
_this.state = {
expandedKeys: [],
autoExpandParent: true,
checkedKeys: ['0-0-0'],
selectedKeys: []
};
_this.onExpand = _this.onExpand.bind(_this);
_this.onCheck = _this.onCheck.bind(_this);
_this.onSelect = _this.onSelect.bind(_this);
return _this;
}
Demo2.prototype.onExpand = function onExpand(expandedKeys) {
console.log('onExpand', arguments);
// if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded children keys.
this.setState({
expandedKeys: expandedKeys,
autoExpandParent: false
});
};
Demo2.prototype.onCheck = function onCheck(checkedKeys) {
this.setState({
checkedKeys: checkedKeys,
selectedKeys: ['0-3', '0-4']
});
};
Demo2.prototype.onSelect = function onSelect(selectedKeys, info) {
console.log('onSelect', info);
this.setState({ selectedKeys: selectedKeys });
};
// keydown的钩子事件
Demo2.prototype.render = function render() {
var loop = function loop(data) {
return data.map(function (item) {
if (item.children) {
return _react2['default'].createElement(
TreeNode,
{ key: item.key, title: item.key, disableCheckbox: item.key === '0-0-0', ext: { 'as': 'sdfa' } },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { key: item.key, title: item.key, isLeaf: true });
});
};
return _react2['default'].createElement(
_src2['default'],
{
checkable: true,
focusable: true,
className: 'demo2 myCls',
onExpand: this.onExpand, expandedKeys: this.state.expandedKeys,
autoExpandParent: this.state.autoExpandParent,
onCheck: this.onCheck,
onSelect: this.onSelect,
keyFun: this.onKeyDown
},
loop(gData)
);
};
return Demo2;
}(_react.Component);
;
exports['default'] = Demo2;
module.exports = exports['default'];
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree 拖拽使用示例
* @description 拖动结点插入到另一个结点后面或者其他的父节点里面。
*
*/
var x = 3;
var y = 2;
var z = 1;
var gData = [];
var generateData = function generateData(_level, _preKey, _tns) {
var preKey = _preKey || '0';
var tns = _tns || gData;
var children = [];
for (var i = 0; i < x; i++) {
var key = preKey + '-' + i;
tns.push({ title: key, key: key });
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
var level = _level - 1;
children.forEach(function (key, index) {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
var TreeNode = _src2['default'].TreeNode;
var Demo3 = function (_Component) {
_inherits(Demo3, _Component);
function Demo3(props) {
_classCallCheck(this, Demo3);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.state = {
gData: gData,
expandedKeys: ['0-0', '0-0-0', '0-0-0-0']
};
_this.onDragEnter = _this.onDragEnter.bind(_this);
_this.onDrop = _this.onDrop.bind(_this);
return _this;
}
Demo3.prototype.onDragEnter = function onDragEnter(info) {
console.log(info);
// expandedKeys 需要受控时设置
// this.setState({
// expandedKeys: info.expandedKeys,
// });
};
Demo3.prototype.onDrop = function onDrop(info) {
console.log(info);
var dropKey = info.node.props.eventKey;
var dragKey = info.dragNode.props.eventKey;
// const dragNodesKeys = info.dragNodesKeys;
var loop = function loop(data, key, callback) {
data.forEach(function (item, index, arr) {
if (item.key === key) {
return callback(item, index, arr);
}
if (item.children) {
return loop(item.children, key, callback);
}
});
};
var data = [].concat(_toConsumableArray(this.state.gData));
var dragObj = void 0;
loop(data, dragKey, function (item, index, arr) {
arr.splice(index, 1);
dragObj = item;
});
if (info.dropToGap) {
var ar = void 0;
var i = void 0;
loop(data, dropKey, function (item, index, arr) {
ar = arr;
i = index;
});
ar.splice(i, 0, dragObj);
} else {
loop(data, dropKey, function (item) {
item.children = item.children || [];
// where to insert 示例添加到尾部,可以是随意位置
item.children.push(dragObj);
});
}
this.setState({
gData: data
});
};
Demo3.prototype.render = function render() {
var loop = function loop(data) {
return data.map(function (item) {
if (item.children && item.children.length) {
return _react2['default'].createElement(
TreeNode,
{ key: item.key, title: item.key },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { key: item.key, title: item.key });
});
};
return _react2['default'].createElement(
_src2['default'],
{
className: 'myCls',
defaultExpandedKeys: this.state.expandedKeys,
draggable: true,
onDragEnter: this.onDragEnter,
onDrop: this.onDrop
},
loop(this.state.gData)
);
};
return Demo3;
}(_react.Component);
;
exports['default'] = Demo3;
module.exports = exports['default'];
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _beeFormControl = __webpack_require__(266);
var _beeFormControl2 = _interopRequireDefault(_beeFormControl);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree可搜索示例
* @description
*
*/
var x = 3;
var y = 2;
var z = 1;
var gData = [];
var generateData = function generateData(_level, _preKey, _tns) {
var preKey = _preKey || '0';
var tns = _tns || gData;
var children = [];
for (var i = 0; i < x; i++) {
var key = preKey + '-' + i;
tns.push({
title: key,
key: key
});
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
var level = _level - 1;
children.forEach(function (key, index) {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
var TreeNode = _src2['default'].TreeNode;
var dataList = [];
var generateList = function generateList(data) {
for (var i = 0; i < data.length; i++) {
var node = data[i];
var key = node.key;
dataList.push({
key: key,
title: key
});
if (node.children) {
generateList(node.children, node.key);
}
}
};
generateList(gData);
var getParentKey = function getParentKey(key, tree) {
var parentKey = void 0;
for (var i = 0; i < tree.length; i++) {
var node = tree[i];
if (node.children) {
if (node.children.some(function (item) {
return item.key === key;
})) {
parentKey = node.key;
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children);
}
}
}
return parentKey;
};
var Demo4 = function (_Component) {
_inherits(Demo4, _Component);
function Demo4(props) {
_classCallCheck(this, Demo4);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onExpand = function (expandedKeys) {
_this.setState({
expandedKeys: expandedKeys,
autoExpandParent: false
});
};
_this.onChange = function (value) {
var expandedKeys = [];
dataList.forEach(function (item) {
if (item.key.indexOf(value) > -1) {
expandedKeys.push(getParentKey(item.key, gData));
}
});
var uniqueExpandedKeys = [];
expandedKeys.forEach(function (item) {
if (item && uniqueExpandedKeys.indexOf(item) === -1) {
uniqueExpandedKeys.push(item);
}
});
_this.setState({
expandedKeys: uniqueExpandedKeys,
searchValue: value,
autoExpandParent: true
});
};
_this.state = {
expandedKeys: [],
searchValue: '',
autoExpandParent: true
};
return _this;
}
Demo4.prototype.render = function render() {
var _state = this.state,
searchValue = _state.searchValue,
expandedKeys = _state.expandedKeys,
autoExpandParent = _state.autoExpandParent;
var loop = function loop(data) {
return data.map(function (item) {
var index = item.key.search(searchValue);
var beforeStr = item.key.substr(0, index);
var afterStr = item.key.substr(index + searchValue.length);
var title = index > -1 ? _react2['default'].createElement(
'span',
null,
beforeStr,
_react2['default'].createElement(
'span',
{ className: 'u-tree-searchable-filter' },
searchValue
),
afterStr
) : _react2['default'].createElement(
'span',
null,
item.key
);
if (item.children) {
return _react2['default'].createElement(
TreeNode,
{ key: item.key, title: title },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { key: item.key, title: title });
});
};
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(_beeFormControl2['default'], {
style: { width: 200 },
placeholder: 'Search',
onChange: this.onChange
}),
_react2['default'].createElement(
_src2['default'],
{
className: 'myCls',
onExpand: this.onExpand,
expandedKeys: expandedKeys,
autoExpandParent: autoExpandParent
},
loop(gData)
)
);
};
return Demo4;
}(_react.Component);
exports['default'] = Demo4;
module.exports = exports['default'];
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree异步数据加载
* @description 当点击展开,异步获取子节点数据
*
*/
var x = 3;
var y = 2;
var z = 1;
var gData = [];
var generateData = function generateData(_level, _preKey, _tns) {
var preKey = _preKey || '0';
var tns = _tns || gData;
var children = [];
for (var i = 0; i < x; i++) {
var key = preKey + '-' + i;
tns.push({
title: key,
key: key
});
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
var level = _level - 1;
children.forEach(function (key, index) {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
var TreeNode = _src2['default'].TreeNode;
function generateTreeNodes(treeNode) {
var arr = [];
var key = treeNode.props.eventKey;
for (var i = 0; i < 3; i++) {
arr.push({
name: 'leaf ' + key + '-' + i,
key: key + '-' + i
});
}
return arr;
}
function setLeaf(treeData, curKey, level) {
var loopLeaf = function loopLeaf(data, lev) {
var l = lev - 1;
data.forEach(function (item) {
if (item.key.length > curKey.length ? item.key.indexOf(curKey) !== 0 : curKey.indexOf(item.key) !== 0) {
return;
}
if (item.children) {
loopLeaf(item.children, l);
} else if (l < 1) {
item.isLeaf = true;
}
});
};
loopLeaf(treeData, level + 1);
}
function getNewTreeData(treeData, curKey, child, level) {
var loop = function loop(data) {
if (level < 1 || curKey.length - 3 > level * 2) return;
data.forEach(function (item) {
if (curKey.indexOf(item.key) === 0) {
if (item.children) {
loop(item.children);
} else {
item.children = child;
}
}
});
};
loop(treeData);
setLeaf(treeData, curKey, level);
}
var Demo5 = function (_Component) {
_inherits(Demo5, _Component);
function Demo5(props) {
_classCallCheck(this, Demo5);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.state = {
treeData: []
};
_this.onSelect = _this.onSelect.bind(_this);
_this.onLoadData = _this.onLoadData.bind(_this);
return _this;
}
Demo5.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
setTimeout(function () {
_this2.setState({
treeData: [{
name: 'pNode 01',
key: '0-0'
}, {
name: 'pNode 02',
key: '0-1'
}, {
name: 'pNode 03',
key: '0-2',
isLeaf: true
}]
});
}, 100);
};
Demo5.prototype.onSelect = function onSelect(info) {
console.log('selected', info);
};
Demo5.prototype.onLoadData = function onLoadData(treeNode) {
var _this3 = this;
return new Promise(function (resolve) {
setTimeout(function () {
var treeData = [].concat(_toConsumableArray(_this3.state.treeData));
getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 2);
_this3.setState({
treeData: treeData
});
resolve();
}, 1000);
});
};
Demo5.prototype.render = function render() {
var loop = function loop(data) {
return data.map(function (item) {
if (item.children) {
return _react2['default'].createElement(
TreeNode,
{ title: item.name, key: item.key },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { title: item.name, key: item.key, isLeaf: item.isLeaf, disabled: item.key === '0-0-0' });
});
};
var treeNodes = loop(this.state.treeData);
return _react2['default'].createElement(
_src2['default'],
{ className: 'myCls', onSelect: this.onSelect, loadData: this.onLoadData },
treeNodes
);
};
return Demo5;
}(_react.Component);
;
exports['default'] = Demo5;
module.exports = exports['default'];
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
var _beeIcon = __webpack_require__(79);
var _beeIcon2 = _interopRequireDefault(_beeIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree基本使用示例自定义图标
* @description 添加openIcon、closeIcon属性
*
*/
var TreeNode = _src2['default'].TreeNode;
var defaultProps = {
keys: ['0-0-0', '0-0-1']
};
var Demo1 = function (_Component) {
_inherits(Demo1, _Component);
function Demo1(props) {
_classCallCheck(this, Demo1);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
var keys = _this.props.keys;
_this.state = {
defaultExpandedKeys: keys,
defaultSelectedKeys: keys,
defaultCheckedKeys: keys
};
return _this;
}
Demo1.prototype.onSelect = function onSelect(info) {
console.log('selected', info);
};
Demo1.prototype.onCheck = function onCheck(info) {
console.log('onCheck', info);
};
Demo1.prototype.render = function render() {
return _react2['default'].createElement(
_src2['default'],
{ className: 'myCls', checkable: true, openIcon: _react2['default'].createElement(_beeIcon2['default'], { type: 'uf-minus' }), closeIcon: _react2['default'].createElement(_beeIcon2['default'], { type: 'uf-plus' }),
defaultExpandedKeys: this.state.defaultExpandedKeys,
defaultSelectedKeys: this.state.defaultSelectedKeys,
defaultCheckedKeys: this.state.defaultCheckedKeys,
onSelect: this.onSelect, onCheck: this.onCheck
},
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1', key: '0-0' },
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-0', key: '0-0-0', disabled: true },
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-0-0', disableCheckbox: true }),
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-0-1' })
),
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-1', key: '0-0-1' },
_react2['default'].createElement(TreeNode, { title: _react2['default'].createElement(
'span',
null,
'sss'
), key: '0-0-1-0' })
)
)
);
};
return Demo1;
}(_react.Component);
Demo1.defaultProps = defaultProps;
exports['default'] = Demo1;
module.exports = exports['default'];
/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
var _beeButton = __webpack_require__(264);
var _beeButton2 = _interopRequireDefault(_beeButton);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree增加节点
* @description 增加节点和拖拽组合使用示例
*
*/
var TreeNode = _src2['default'].TreeNode;
var Demo7 = function (_Component) {
_inherits(Demo7, _Component);
function Demo7(props) {
_classCallCheck(this, Demo7);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onDragEnter = function (info) {
console.log(info);
// expandedKeys 需要受控时设置
// this.setState({
// expandedKeys: info.expandedKeys,
// });
};
_this.onDrop = function (info) {
console.log(info);
var dropKey = info.node.props.eventKey;
var dragKey = info.dragNode.props.eventKey;
// const dragNodesKeys = info.dragNodesKeys;
var loop = function loop(data, key, callback) {
data.forEach(function (item, index, arr) {
if (item.key === key) {
return callback(item, index, arr);
}
if (item.children) {
return loop(item.children, key, callback);
}
});
};
var data = [].concat(_toConsumableArray(_this.state.treeData));
var dragObj = void 0;
loop(data, dragKey, function (item, index, arr) {
arr.splice(index, 1);
dragObj = item;
});
if (info.dropToGap) {
var ar = void 0;
var i = void 0;
loop(data, dropKey, function (item, index, arr) {
ar = arr;
i = index;
});
ar.splice(i, 0, dragObj);
} else {
loop(data, dropKey, function (item) {
item.children = item.children || [];
// where to insert 示例添加到尾部,可以是随意位置
item.children.push(dragObj);
});
}
_this.setState({
treeData: data
});
};
_this.state = {
treeData: [],
defaultExpandedKeys: ['0-0', '0-1', '0-2'],
parentNode: {}
};
_this.onSelect = _this.onSelect.bind(_this);
_this.addNode = _this.addNode.bind(_this);
_this.clickFun = _this.clickFun.bind(_this);
_this.getNodeByKey = _this.getNodeByKey.bind(_this);
_this.parentNode = null;
return _this;
}
Demo7.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
setTimeout(function () {
_this2.setState({
treeData: [{
name: 'pNode 01',
key: '0-0',
children: [{
name: 'leaf 0-0-0',
key: '0-0-0'
}, {
name: 'leaf 0-0-1',
key: '0-0-1'
}]
}, {
name: 'pNode 02',
key: '0-1',
children: [{
name: 'leaf 0-1-0',
key: '0-1-0'
}, {
name: 'leaf 0-1-1',
key: '0-1-1'
}]
}, {
name: 'pNode 03',
key: '0-2',
isLeaf: true
}]
});
}, 100);
};
/**
* 增加节点
* @param string prKey [父节点key]
* @param object nodeItem [子节点信息]
*/
Demo7.prototype.addNode = function addNode(prKey, nodeItem) {
var data = this.state.treeData;
var parNode = void 0;
if (prKey) {
// 如果prKey存在则搜索父节点进行添加
parNode = this.getNodeByKey(data, prKey);
//如果父节点存在的话,添加到父节点上
if (parNode) {
if (!parNode.children) {
parNode.children = [];
}
// 如果key不存在就动态生成一个
if (!nodeItem.key) {
nodeItem.key = prKey + parNode.children.length + 1;
}
parNode.children.push(nodeItem);
}
} else {
// 没有穿prKey添加到根下成为一级节点
if (!nodeItem.key) {
nodeItem.key = "0-" + data.length + 1;
}
data.push(nodeItem);
}
this.setState({
data: data
});
};
Demo7.prototype.getNodeByKey = function getNodeByKey(data, key) {
var _this3 = this;
if (!this.parentNode) {
data.find(function (item) {
if (item.key === key) {
console.log('item.name---' + item.name);
_this3.parentNode = item;
return true;
} else if (item.children) {
return _this3.getNodeByKey(item.children, key);
}
});
}
return this.parentNode;
};
Demo7.prototype.onSelect = function onSelect(info) {
console.log('selected', info);
};
/**
* 点击button事件
*/
Demo7.prototype.clickFun = function clickFun() {
var prKey = void 0,
nodeItem = void 0;
prKey = '0-1';
nodeItem = {
name: 'leaf 0-0-4'
};
this.addNode(prKey, nodeItem);
};
Demo7.prototype.render = function render() {
var loop = function loop(data) {
return data.map(function (item) {
if (item.children) {
return _react2['default'].createElement(
TreeNode,
{ title: item.name, key: item.key },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { title: item.name, key: item.key, isLeaf: item.isLeaf, disabled: item.key === '0-0-0' });
});
};
var treeNodes = loop(this.state.treeData);
console.log('defaultKeys--' + this.state.defaultExpandedKeys);
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
_beeButton2['default'],
{ colors: 'primary', onClick: this.clickFun },
'\u589E\u52A0\u8282\u70B9'
),
_react2['default'].createElement(
_src2['default'],
{
className: 'myCls',
onSelect: this.onSelect,
defaultExpandedKeys: this.state.defaultExpandedKeys,
draggable: true,
onDragEnter: this.onDragEnter,
onDrop: this.onDrop },
treeNodes
)
);
};
return Demo7;
}(_react.Component);
;
exports['default'] = Demo7;
module.exports = exports['default'];
/***/ }),
/* 311 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
var _beeButton = __webpack_require__(264);
var _beeButton2 = _interopRequireDefault(_beeButton);
var _beeIcon = __webpack_require__(79);
var _beeIcon2 = _interopRequireDefault(_beeIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree 节点可编辑
* @description 鼠标移动到节点上点击编辑图标进行编辑。e.node.props.eventKey代表当前节点key值。editKey指当前操作的节点key
*/
var TreeNode = _src2['default'].TreeNode;
var Demo8 = function (_Component) {
_inherits(Demo8, _Component);
function Demo8(props) {
_classCallCheck(this, Demo8);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onMouseEnter = function (e) {
_this.setState({
isHover: e.node.props.eventKey
});
};
_this.onMouseLeave = function (e, treenode) {
_this.setState({
isHover: "",
editKey: ""
});
};
_this.editRender = function (item) {
_this.setState({
editKey: item.key
});
};
_this.nodechange = function (item, value) {
item.name = value;
};
_this.renderTreeTitle = function (item) {
var titleIcon = void 0,
titleInfo = void 0;
//编辑时input框
if (_this.state.editKey == item.key) {
titleInfo = _react2['default'].createElement('input', { type: 'text', id: 'itemKey', defaultValue: item.name, onChange: function onChange(e) {
return _this.nodechange(item, e.target.value);
} });
} else {
titleInfo = _react2['default'].createElement(
'span',
{ className: 'title-middle' },
item.name
);
}
//编辑图标
if (_this.state.isHover == item.key) {
titleIcon = _react2['default'].createElement(_beeIcon2['default'], { className: 'title-middle edit-icon', type: 'uf-pencil', onClick: function onClick(e) {
return _this.editRender(item);
} });
}
return _react2['default'].createElement(
'div',
{ className: 'title-con' },
titleInfo,
titleIcon
);
};
_this.componentDidMount = function () {
setTimeout(function () {
_this.setState({
treeData: [{
name: 'pNode 01',
key: '0-0',
children: [{
name: 'leaf 0-0-0',
key: '0-0-0'
}, {
name: 'leaf 0-0-1',
key: '0-0-1'
}]
}, {
name: 'pNode 02',
key: '0-1',
children: [{
name: 'leaf 0-1-0',
key: '0-1-0'
}, {
name: 'leaf 0-1-1',
key: '0-1-1'
}]
}, {
name: 'pNode 03',
key: '0-2',
isLeaf: true
}]
});
}, 100);
};
_this.state = {
treeData: [],
isHover: "",
editKey: ""
};
return _this;
}
Demo8.prototype.render = function render() {
var _this2 = this;
var loop = function loop(data) {
return data.map(function (item) {
if (item.children) {
return _react2['default'].createElement(
TreeNode,
{ title: _this2.renderTreeTitle(item), key: item.key },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { title: _this2.renderTreeTitle(item), key: item.key, isLeaf: item.isLeaf, disabled: item.key === '0-0-0' });
});
};
var treeNodes = loop(this.state.treeData);
return _react2['default'].createElement(
_src2['default'],
{ onMouseLeave: this.onMouseLeave, onMouseEnter: this.onMouseEnter, className: 'myCls' },
treeNodes
);
};
return Demo8;
}(_react.Component);
exports['default'] = Demo8;
module.exports = exports['default'];
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title 连接线Tree
* @description
*
*/
var TreeNode = _src2['default'].TreeNode;
var Demo9 = function (_Component) {
_inherits(Demo9, _Component);
function Demo9(props) {
_classCallCheck(this, Demo9);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
var keys = _this.props.keys;
_this.state = {
defaultExpandedKeys: keys
};
return _this;
}
Demo9.prototype.render = function render() {
return _react2['default'].createElement(
_src2['default'],
{ className: 'myCls', showLine: true, checkable: true, defaultExpandAll: true },
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1', key: '0-0' },
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-0', key: '0-0-0' },
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-0-0' }),
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-0-1' })
),
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-1', key: '0-0-1' },
_react2['default'].createElement(TreeNode, { title: _react2['default'].createElement(
'span',
null,
'sss'
), key: '0-0-1-0' })
)
)
);
};
return Demo9;
}(_react.Component);
exports['default'] = Demo9;
module.exports = exports['default'];
/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title Tree基本使用示例
* @description 如何获取选中对象自定义对象和数据
*
*/
var TreeNode = _src2['default'].TreeNode;
var defaultProps = {
keys: ['0-0-0', '0-0-1']
};
var Demo10 = function (_Component) {
_inherits(Demo10, _Component);
function Demo10(props) {
_classCallCheck(this, Demo10);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onCheck = function (checkedKeys) {
var self = _this;
console.log('onCheck', checkedKeys);
var cks = {
checked: checkedKeys.checked || checkedKeys
};
// this.setState({checkedKeys:cks});
};
_this.onDoubleClick = function (key, treeNode) {
console.log('---onDblClick---' + key + '--treeNode--' + treeNode);
};
var keys = _this.props.keys;
_this.state = {
defaultExpandedKeys: keys,
defaultSelectedKeys: keys,
defaultCheckedKeys: keys
// checkedKeys: {checked:keys},
};
return _this;
}
/**
* 获取当前选中行的item对象。
* @param {*} value
*/
Demo10.prototype.onSelect = function onSelect(selectedKeys, e) {
console.log(selectedKeys + ' selected'); //获取key
var currentObject = {};
currentObject.title = e.node.props.title; //获取选中对象的数据
currentObject.key = e.node.props.eventKey;
console.log(currentObject);
};
Demo10.prototype.render = function render() {
return _react2['default'].createElement(
_src2['default'],
{ className: 'myCls', showLine: true, checkable: true,
defaultExpandedKeys: this.state.defaultExpandedKeys,
defaultSelectedKeys: this.state.defaultSelectedKeys,
defaultCheckedKeys: this.state.defaultCheckedKeys,
checkStrictly: true,
onSelect: this.onSelect, onCheck: this.onCheck,
onDoubleClick: this.onDoubleClick
},
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1', key: '0-0' },
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-0', key: '0-0-0', disabled: true },
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-0-0', disableCheckbox: true }),
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-0-1' })
),
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-1', key: '0-0-1' },
_react2['default'].createElement(TreeNode, { title: _react2['default'].createElement(
'span',
null,
'sss'
), key: '0-0-1-0' })
),
_react2['default'].createElement(
TreeNode,
{ title: 'parent 1-2', key: '0-0-2' },
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-2-0' }),
_react2['default'].createElement(TreeNode, { title: 'leaf', key: '0-0-2-1' })
)
)
);
};
return Demo10;
}(_react.Component);
Demo10.defaultProps = defaultProps;
exports['default'] = Demo10;
module.exports = exports['default'];
/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title 用户自定义节点属性ext
* @description 业务中扩展的数据可以定义在ext属性中用户可以在TreeNode节点中获取ext属性。此例中将treeNode的数据存放在了ext中方便用户获取。
* 
*/
var x = 6;
var y = 5;
var z = 2;
var gData = [];
var generateData = function generateData(_level, _preKey, _tns) {
var preKey = _preKey || '0';
var tns = _tns || gData;
var children = [];
for (var i = 0; i < x; i++) {
var key = preKey + '-' + i;
tns.push({ title: key, key: key });
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
var level = _level - 1;
children.forEach(function (key, index) {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
var TreeNode = _src2['default'].TreeNode;
var Demo11 = function (_Component) {
_inherits(Demo11, _Component);
function Demo11(props) {
_classCallCheck(this, Demo11);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onKeyDown = function (e, treeNode) {
console.log('***', e);
return false;
};
_this.state = {
expandedKeys: [],
autoExpandParent: true,
checkedKeys: ['0-0-0'],
selectedKeys: []
};
_this.onExpand = _this.onExpand.bind(_this);
_this.onCheck = _this.onCheck.bind(_this);
_this.onSelect = _this.onSelect.bind(_this);
return _this;
}
Demo11.prototype.onExpand = function onExpand(expandedKeys, nodeInfo) {
console.log('onExpand---显示ext数据', nodeInfo.node.props.ext.data);
this.setState({
expandedKeys: expandedKeys,
autoExpandParent: false
});
};
Demo11.prototype.onCheck = function onCheck(checkedKeys) {
this.setState({
checkedKeys: checkedKeys,
selectedKeys: ['0-3', '0-4']
});
};
Demo11.prototype.onSelect = function onSelect(selectedKeys, info) {
console.log('onSelect', info);
this.setState({ selectedKeys: selectedKeys });
};
// keydown的钩子事件
Demo11.prototype.render = function render() {
var loop = function loop(data) {
return data.map(function (item) {
if (item.children) {
return _react2['default'].createElement(
TreeNode,
{ key: item.key, title: item.key, disableCheckbox: item.key === '0-0-0', ext: { 'data': item } },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { key: item.key, title: item.key, isLeaf: true });
});
};
return _react2['default'].createElement(
_src2['default'],
{
checkable: true,
focusable: true,
className: 'demo2 myCls',
onExpand: this.onExpand, expandedKeys: this.state.expandedKeys,
autoExpandParent: this.state.autoExpandParent,
onCheck: this.onCheck,
onSelect: this.onSelect,
keyFun: this.onKeyDown
},
loop(gData)
);
};
return Demo11;
}(_react.Component);
;
exports['default'] = Demo11;
module.exports = exports['default'];
/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title 根据 treeData 数组渲染树节点
* @description 设置 treeData 属性,则不需要手动构造 TreeNode 节点key 在整个树范围内唯一)
*/
var treeData = [{
title: '0-0',
key: '0-0',
ext: '自定义属性',
children: [{
title: '0-0-0',
key: '0-0-0',
children: [{ title: '0-0-0-0', key: '0-0-0-0' }, { title: '0-0-0-1', key: '0-0-0-1' }, { title: '0-0-0-2', key: '0-0-0-2' }]
}, {
title: '0-0-1',
key: '0-0-1',
children: [{ title: '0-0-1-0', key: '0-0-1-0' }, { title: '0-0-1-1', key: '0-0-1-1' }, { title: '0-0-1-2', key: '0-0-1-2' }]
}, {
title: '0-0-2',
key: '0-0-2'
}]
}, {
title: '0-1',
key: '0-1',
children: [{ title: '0-1-0-0', key: '0-1-0-0' }, { title: '0-1-0-1', key: '0-1-0-1' }, { title: '0-1-0-2', key: '0-1-0-2' }]
}, {
title: '0-2',
key: '0-2',
ext: '自定义属性'
}];
var Demo12 = function (_Component) {
_inherits(Demo12, _Component);
function Demo12() {
var _temp, _this, _ret;
_classCallCheck(this, Demo12);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = {
expandedKeys: ['0-0-0', '0-0-1'],
autoExpandParent: true,
checkedKeys: ['0-0-0'],
selectedKeys: []
}, _this.onExpand = function (expandedKeys) {
console.log('onExpand', expandedKeys);
// if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded children keys.
_this.setState({
expandedKeys: expandedKeys,
autoExpandParent: false
});
}, _this.onCheck = function (checkedKeys) {
console.log('onCheck', checkedKeys);
_this.setState({ checkedKeys: checkedKeys });
}, _this.onSelect = function (selectedKeys, info) {
console.log('onSelect', info);
_this.setState({ selectedKeys: selectedKeys });
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Demo12.prototype.render = function render() {
return _react2['default'].createElement(_src2['default'], {
checkable: true,
treeData: treeData,
onExpand: this.onExpand,
expandedKeys: this.state.expandedKeys,
autoExpandParent: this.state.autoExpandParent,
onCheck: this.onCheck,
checkedKeys: this.state.checkedKeys,
onSelect: this.onSelect,
selectedKeys: this.state.selectedKeys
});
};
return Demo12;
}(_react.Component);
exports['default'] = Demo12;
module.exports = exports['default'];
/***/ }),
/* 316 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _beeButton = __webpack_require__(264);
var _beeButton2 = _interopRequireDefault(_beeButton);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /**
*
* @title 滚动加载树节点
* @description 适用于大数据场景。注意:使用懒加载,需要通过 treeData 属性传入完整的数据结构,并设置 lazyLoad = {true}。可视区域的高度可以自定义,在 Tree 组件外层包裹一层div即可。
*/
var TreeNode = _src2['default'].TreeNode;
var x = 1000;
var y = 1;
var z = 1;
var gData = [];
var generateData = function generateData(_level, _preKey, _tns) {
var preKey = _preKey || '0';
var tns = _tns || gData;
var children = [];
for (var i = 0; i < x; i++) {
var key = preKey + '-' + i;
tns.push({ title: key, key: key });
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
var level = _level - 1;
children.forEach(function (key, index) {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
var data = [].concat(_toConsumableArray(new Array(10000))).map(function (e, i) {
var rs = { key: i + 'a', title: i + 'a' };
return rs;
});
var Demo13 = function (_Component) {
_inherits(Demo13, _Component);
function Demo13(props) {
_classCallCheck(this, Demo13);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onKeyDown = function (e, treeNode) {
console.log('***', e);
return false;
};
_this.renderTreeNodes = function (data) {
var loop = function loop(data) {
return data.map(function (item) {
if (item.children) {
return _react2['default'].createElement(
TreeNode,
{ key: item.key, title: item.key, isLeaf: item.isLeaf },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { key: item.key, title: item.key, isLeaf: true });
});
};
return loop(data);
};
_this.changeTreeData = function () {
_this.setState({
treeData: gData
});
};
_this.state = {
expandedKeys: ['0-0', '0-1', '0-2', '0-3', '0-4', '0-5', '0-6', '0-0-0', '0-0-1'],
autoExpandParent: true,
checkedKeys: ['0-0-0'],
selectedKeys: [],
treeData: data
};
_this.onExpand = _this.onExpand.bind(_this);
_this.onCheck = _this.onCheck.bind(_this);
_this.onSelect = _this.onSelect.bind(_this);
return _this;
}
Demo13.prototype.onExpand = function onExpand(expandedKeys, nodeInfo) {
// console.log('onExpand---显示ext数据', nodeInfo.node.props.ext.data);
this.setState({
expandedKeys: expandedKeys,
autoExpandParent: false
});
};
Demo13.prototype.onCheck = function onCheck(checkedKeys) {
this.setState({
checkedKeys: checkedKeys,
selectedKeys: ['0-3', '0-4']
});
};
Demo13.prototype.onSelect = function onSelect(selectedKeys, info) {
console.log('onSelect', info);
this.setState({ selectedKeys: selectedKeys });
};
// keydown的钩子事件
//使用 treeData 渲染树节点时,可使用该函数自定义节点显示内容(非必须)
//注意isLeaf 属性是必传的,否则节点层级和展示会有问题
Demo13.prototype.render = function render() {
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
_beeButton2['default'],
{ onClick: this.changeTreeData },
'\u6539\u53D8\u6570\u636E\u6E90'
),
_react2['default'].createElement(
'div',
{ style: { height: '300px', overflow: 'auto' } },
_react2['default'].createElement(_src2['default'], {
checkable: true,
focusable: true,
treeData: this.state.treeData,
lazyLoad: true,
debounceDuration: 100,
renderTreeNodes: this.renderTreeNodes,
onExpand: this.onExpand,
defaultExpandAll: true,
expandedKeys: this.state.expandedKeys,
autoExpandParent: this.state.autoExpandParent,
onCheck: this.onCheck,
onSelect: this.onSelect,
keyFun: this.onKeyDown
})
)
);
};
return Demo13;
}(_react.Component);
;
exports['default'] = Demo13;
module.exports = exports['default'];
/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _src = __webpack_require__(296);
var _src2 = _interopRequireDefault(_src);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
*
* @title 自定义滚动容器
* @description 使用 getScrollParent 设置需要监听滚动事件的容器。
*/
var TreeNode = _src2['default'].TreeNode;
var x = 1000;
var y = 1;
var z = 1;
var gData = [];
var generateData = function generateData(_level, _preKey, _tns) {
var preKey = _preKey || '0';
var tns = _tns || gData;
var children = [];
for (var i = 0; i < x; i++) {
var key = preKey + '-' + i;
tns.push({ title: key, key: key });
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
var level = _level - 1;
children.forEach(function (key, index) {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
var Demo14 = function (_Component) {
_inherits(Demo14, _Component);
function Demo14(props) {
_classCallCheck(this, Demo14);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.onKeyDown = function (e, treeNode) {
console.log('***', e);
return false;
};
_this.renderTreeNodes = function (data) {
var loop = function loop(data) {
return data.map(function (item) {
if (item.children) {
return _react2['default'].createElement(
TreeNode,
{ key: item.key, title: item.key, isLeaf: item.isLeaf },
loop(item.children)
);
}
return _react2['default'].createElement(TreeNode, { key: item.key, title: item.key, isLeaf: true });
});
};
return loop(data);
};
_this.state = {
expandedKeys: ['0-0', '0-1', '0-2', '0-3', '0-4', '0-5', '0-6', '0-0-0', '0-0-1'],
autoExpandParent: true,
checkedKeys: ['0-0-0'],
selectedKeys: []
};
_this.onExpand = _this.onExpand.bind(_this);
_this.onCheck = _this.onCheck.bind(_this);
_this.onSelect = _this.onSelect.bind(_this);
return _this;
}
Demo14.prototype.onExpand = function onExpand(expandedKeys, nodeInfo) {
// console.log('onExpand---显示ext数据', nodeInfo.node.props.ext.data);
this.setState({
expandedKeys: expandedKeys,
autoExpandParent: false
});
};
Demo14.prototype.onCheck = function onCheck(checkedKeys) {
this.setState({
checkedKeys: checkedKeys,
selectedKeys: ['0-3', '0-4']
});
};
Demo14.prototype.onSelect = function onSelect(selectedKeys, info) {
console.log('onSelect', info);
this.setState({ selectedKeys: selectedKeys });
};
// keydown的钩子事件
//使用 treeData 渲染树节点时,可使用该函数自定义节点显示内容(非必须)
//注意isLeaf 属性是必传的,否则节点层级和展示会有问题
Demo14.prototype.render = function render() {
return _react2['default'].createElement(
'div',
{ className: 'container', style: { height: '300px', overflow: 'auto' } },
_react2['default'].createElement(
'div',
null,
_react2['default'].createElement(_src2['default'], {
checkable: true,
focusable: true,
treeData: gData,
lazyLoad: true,
renderTreeNodes: this.renderTreeNodes,
onExpand: this.onExpand,
defaultExpandAll: true,
expandedKeys: this.state.expandedKeys,
autoExpandParent: this.state.autoExpandParent,
onCheck: this.onCheck,
onSelect: this.onSelect,
keyFun: this.onKeyDown,
getScrollContainer: function getScrollContainer() {
return document.querySelector('.container');
}
})
)
);
};
return Demo14;
}(_react.Component);
;
exports['default'] = Demo14;
module.exports = exports['default'];
/***/ })
/******/ ]);
//# sourceMappingURL=demo.js.map