diff --git a/.browserslistrc b/.browserslistrc new file mode 100644 index 0000000..214388f --- /dev/null +++ b/.browserslistrc @@ -0,0 +1,3 @@ +> 1% +last 2 versions +not dead diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..1b1fd6b --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,19 @@ +module.exports = { + root: true, + env: { + node: true, + }, + extends: [ + "plugin:vue/essential", + "eslint:recommended", + "@vue/typescript/recommended", + ], + parserOptions: { + ecmaVersion: 2020, + }, + rules: { + "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", + "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off", + "@typescript-eslint/ban-ts-comment": "off", + }, +}; diff --git a/.gitignore b/.gitignore index 70dae2f..a70e82e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,17 +1,17 @@ .DS_Store node_modules +dist + # local env files .env.local .env.*.local -# local files -__local* - # Log files npm-debug.log* yarn-debug.log* yarn-error.log* +pnpm-debug.log* # Editor directories and files .idea @@ -20,4 +20,4 @@ yarn-error.log* *.ntvs* *.njsproj *.sln -*.sw* +*.sw? diff --git a/CHANGELOG.md b/CHANGELOG.md index 502a715..9273eb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,50 +2,46 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. -## [2.0.11.beta.3](https://github.com/phphe/he-tree-vue/compare/v2.0.10...v2.0.11.beta.3) (2021-06-26) +## [4.0.0-beta](https://github.com/phphe/he-tree-vue/compare/v2.0.10...v4.0.0-beta) (2021-08-03) ### Bug Fixes * **draggable plugin:** correct the value of store.targetPath ([21a5bf7](https://github.com/phphe/he-tree-vue/commit/21a5bf700048e90ed03a31397c797aa41c104fbe)) -## [2.0.11.beta-2](https://github.com/phphe/he-tree-vue/compare/v2.0.10...v2.0.11.beta-2) (2021-06-26) +### [3.0.3](https://github.com/phphe/he-tree-vue/compare/v3.0.2...v3.0.3) (2021-04-16) ### Bug Fixes -* **draggable plugin:** correct the value of store.targetPath ([21a5bf7](https://github.com/phphe/he-tree-vue/commit/21a5bf700048e90ed03a31397c797aa41c104fbe)) +* **draggable plugin:** fix node insert error after drop ([04de941](https://github.com/phphe/he-tree-vue/commit/04de9418e893fa3390de6a3863e9abcc47d200c1)), closes [#51](https://github.com/phphe/he-tree-vue/issues/51) -## [2.0.11.beta](https://github.com/phphe/he-tree-vue/compare/v2.0.10...v2.0.11.beta) (2021-06-26) +### [3.0.2](https://github.com/phphe/he-tree-vue/compare/v3.0.1...v3.0.2) (2021-04-12) ### Bug Fixes -* **draggable plugin:** correct the value of store.targetPath ([21a5bf7](https://github.com/phphe/he-tree-vue/commit/21a5bf700048e90ed03a31397c797aa41c104fbe)) +* **draggable plugin:** wrong result when move downwards in same level ([9124ec1](https://github.com/phphe/he-tree-vue/commit/9124ec19c72836b3927d1c4065fa1fd135689ab6)) -### [2.0.10](https://github.com/phphe/he-tree-vue/compare/v2.0.9...v2.0.10) (2021-04-16) +### [3.0.1](https://github.com/phphe/he-tree-vue/compare/v3.0.0...v3.0.1) (2021-03-30) ### Bug Fixes -* **draggable plugin:** fix node insert error after drop ([337a09b](https://github.com/phphe/he-tree-vue/commit/337a09baf8ef88532c102a3e414905e7e3e850aa)), closes [#51](https://github.com/phphe/he-tree-vue/issues/51) - -### [2.0.9](https://github.com/phphe/he-tree-vue/compare/v2.0.8...v2.0.9) (2021-04-12) +* **draggable plugin:** fix change even ([72c1b08](https://github.com/phphe/he-tree-vue/commit/72c1b08785a895040ce65f6175cf5db093383173)) +## [3.0.0](https://github.com/phphe/he-tree-vue/compare/v2.0.7-beta.3...v3.0.0) (2020-12-13) -### Bug Fixes -* **draggable plugin:** wrong result when move downwards in same level ([cb64dac](https://github.com/phphe/he-tree-vue/commit/cb64dac830c6b2b5e962a556895e3cfd8bddb2a6)), closes [#50](https://github.com/phphe/he-tree-vue/issues/50) +### Features -### [2.0.8](https://github.com/phphe/he-tree-vue/compare/v2.0.7...v2.0.8) (2021-03-30) +* **all:** update for vue3 ([fd2e1ac](https://github.com/phphe/he-tree-vue/commit/fd2e1acdf001f23a5e87528a13361eb7828fa62b)) +* **types:** update types declaration for vue3 ([175c0f2](https://github.com/phphe/he-tree-vue/commit/175c0f27e7a19f17befe8784f1b289a90cb50500)) ### Bug Fixes -* **draggable plugin:** decrease delay before remove mask tree ([d9074c2](https://github.com/phphe/he-tree-vue/commit/d9074c27e848139186ad9a694d6da70f6e2a4517)) -* **draggable plugin:** fix change event ([7c6e1e7](https://github.com/phphe/he-tree-vue/commit/7c6e1e7ba17d26ff76e323d73085063e5b3578c7)) - -### [2.0.7](https://github.com/phphe/he-tree-vue/compare/v2.0.7-beta.3...v2.0.7) (2020-12-13) +* **dist:** use .js instead of .vue to fix 'render overrided issue' ([5b2fcc3](https://github.com/phphe/he-tree-vue/commit/5b2fcc3ca3d209999cd9ce400f0af65cb9421dad)) ### [2.0.7-beta.3](https://github.com/phphe/he-tree-vue/compare/v2.0.7-beta.2...v2.0.7-beta.3) (2020-12-13) diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 75bd7e4..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017-2020 phphe - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md index e4231df..26ed97b 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,15 @@ # he-tree-vue + +**This project is no longer maintained, please move to the new monorepo [he-tree](https://github.com/phphe/he-tree).** + +**本项目不再维护, 请移步到新的 monorepo [he-tree](https://github.com/phphe/he-tree).** + A draggable sortable vue tree component, with dragging placeholder, types definition. Vue3 supported. [Demo](https://he-tree-vue.phphe.com), [Document](https://he-tree-vue.phphe.com) -可拖拽可排序vue树组件, 支持拖拽占位盒, typescript定义文件, vue3. [演示](https://he-tree-vue.phphe.com/zh), [文档](https://he-tree-vue.phphe.com/zh) +可拖拽可排序 vue 树组件, 支持拖拽占位盒, typescript 定义文件, vue3. [演示](https://he-tree-vue.phphe.com/zh), [文档](https://he-tree-vue.phphe.com/zh) ![image](https://github.com/phphe/he-tree-vue/blob/master/public/demo.gif?raw=true) ## License -[MIT](http://opensource.org/licenses/MIT) \ No newline at end of file + +[MIT](http://opensource.org/licenses/MIT) diff --git a/babel.config.js b/babel.config.js index df07c5d..e955840 100644 --- a/babel.config.js +++ b/babel.config.js @@ -1,6 +1,5 @@ module.exports = { presets: [ - '@vue/cli-plugin-babel/preset', - ], - plugins: [], + '@vue/cli-plugin-babel/preset' + ] } diff --git a/dist/he-tree-vue.cjs.js b/dist/he-tree-vue.cjs.js deleted file mode 100644 index 4601f2a..0000000 --- a/dist/he-tree-vue.cjs.js +++ /dev/null @@ -1,2075 +0,0 @@ -/*! - * he-tree-vue v2.0.11.beta.3 - * (c) phphe (https://github.com/phphe) - * Homepage: https://he-tree-vue.phphe.com - * Released under the MIT License. - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var _toConsumableArray = _interopDefault(require('@babel/runtime/helpers/toConsumableArray')); -var _defineProperty = _interopDefault(require('@babel/runtime/helpers/defineProperty')); -var hp = require('helper-js'); -var vf = require('vue-functions'); -var __vue_normalize__ = _interopDefault(require('vue-runtime-helpers/dist/normalize-component.js')); -var Vue = _interopDefault(require('vue')); -var _regeneratorRuntime = _interopDefault(require('@babel/runtime/regenerator')); -var _asyncToGenerator = _interopDefault(require('@babel/runtime/helpers/asyncToGenerator')); -var draggableHelper = _interopDefault(require('draggable-helper')); - -function cloneTreeData(treeData, opt) { - return new hp.TreeData(treeData).clone(opt); -} -function walkTreeData(treeData, handler, opt) { - return new hp.TreeData(treeData).walk(handler, opt); -} -function getPureTreeData(treeData) { - var opt = { - afterNodeCreated: function afterNodeCreated(newNode) { - Object.keys(newNode).forEach(function (key) { - if (key[0] === '$') { - delete newNode[key]; - } - }); - } - }; - return cloneTreeData(treeData, opt); -} - -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) { _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; } - -var template = function template(h) { - var _this = this; - - // convert undefined to empty str - var noUndefined = function noUndefined(str) { - return str ? str : ''; - }; // tree tpl, to render recursively - - - var childrenListTpl = function childrenListTpl(nodes, parent, parentPath) { - var indentStyle = _defineProperty({}, !_this.rtl ? 'paddingLeft' : 'paddingRight', parentPath.length * _this.indent + 'px'); - - var branchTpl = function branchTpl(node, index) { - var path = [].concat(_toConsumableArray(parentPath), [index]); - var transitionComponent = _this.foldingTransition || 'transition'; - - var slotDefault = function slotDefault() { - var original = function original() { - if (_this.$scopedSlots.default) { - return _this.$scopedSlots.default({ - node: node, - index: index, - path: path, - tree: _this - }); - } else if (_this.$slots.default) { - return _this.$slots.default; - } else { - return node.text; - } - }; - - if (_this.overrideSlotDefault) { - return _this.overrideSlotDefault({ - node: node, - index: index, - path: path, - tree: _this - }, original); - } else { - return original(); - } - }; - - var nodebackStyle = indentStyle; - - if (node.$nodeBackStyle) { - nodebackStyle = _objectSpread(_objectSpread({}, nodebackStyle), node.$nodeBackStyle); - } - - return h("div", { - "class": "tree-branch ".concat(noUndefined(node.$branchClass), " ").concat(noUndefined(node.$hidden && 'he-tree--hidden')), - "style": node.$branchStyle || {}, - "attrs": { - "data-tree-node-path": path.join(',') - } - }, [h("div", { - "class": "tree-node-back ".concat(noUndefined(node.$nodeBackClass)), - "style": nodebackStyle || {} - }, [h("div", { - "class": "tree-node ".concat(noUndefined(node.$nodeClass)), - "style": node.$nodeStyle || {} - }, [slotDefault()])]), (node.children && node.children.length) > 0 && h(transitionComponent, { - "attrs": { - "name": _this.$props.foldingTransitionName - } - }, [!node.$folded && childrenListTpl(node.children, node, path)])]); - }; - - return h("div", { - "class": "tree-children ".concat(noUndefined(parent === _this.rootNode && 'tree-root'), " ").concat(noUndefined(parent.$childrenClass)), - "style": parent.$childrenStyle || {} - }, [nodes.map(branchTpl)]); - }; - - return h("div", { - "class": "he-tree ".concat(this.treeClass, " ").concat(noUndefined(this.rtl && 'he-tree--rtl')), - "attrs": { - "data-tree-id": this.treeId - } - }, [this.blockHeader && this.blockHeader(), childrenListTpl(this.rootNode.children, this.rootNode, []), this.blockFooter && this.blockFooter()]); -}; - -var trees = {}; -var Tree = { - render: template, - mixins: [vf.updatablePropsEvenUnbound({ - value: { - $localName: 'treeData', - required: true - } - }), vf.hookHelper], - props: { - indent: { - type: Number, - default: 20 - }, - rtl: { - type: Boolean - }, - rootNode: { - default: function _default(is) { - return {}; - } - } - }, - // components: {}, - data: function data() { - return { - trees: trees, - treeClass: '', - treeId: hp.randString() - }; - }, - // computed: {}, - watch: { - treeData: { - immediate: true, - handler: function handler(treeData) { - this._TreeDataHelper = new hp.TreeData(this.treeData); - } - } - }, - methods: { - iteratePath: function iteratePath(path, opt) { - return this._TreeDataHelper.iteratePath(path, opt); - }, - getTreeVmByTreeEl: function getTreeVmByTreeEl(treeEl) { - return this.trees[treeEl.getAttribute('data-tree-id')]; - }, - getAllNodesByPath: function getAllNodesByPath(path) { - return this._TreeDataHelper.getAllNodes(path); - }, - getNodeByPath: function getNodeByPath(path) { - return this._TreeDataHelper.getNode(path); - }, - getPathByBranchEl: function getPathByBranchEl(branchEl) { - return branchEl.getAttribute('data-tree-node-path').split(',').map(function (v) { - return parseInt(v); - }); - }, - getBranchElByPath: function getBranchElByPath(path) { - return this.$el.querySelector("[data-tree-node-path='".concat(path.join(','), "']")); - }, - getNodeByBranchEl: function getNodeByBranchEl(branchEl) { - return this.getNodeByPath(this.getPathByBranchEl(branchEl)); - }, - getNodeParentByPath: function getNodeParentByPath(path) { - return this._TreeDataHelper.getNodeParent(path); - }, - removeNodeByPath: function removeNodeByPath(path) { - return this._TreeDataHelper.removeNode(path); - }, - walkTreeData: function walkTreeData$1(handler, opt) { - return walkTreeData(this.treeData, handler, opt); - }, - cloneTreeData: function cloneTreeData$1(opt) { - return cloneTreeData(this.treeData, opt); - }, - // return cloned new tree data without property witch starts with `$` - getPureTreeData: function getPureTreeData$1() { - return getPureTreeData(this.treeData); - } - }, - created: function created() { - var _this2 = this; - - // - var updateRootNode = function updateRootNode() { - _this2.$set(_this2.rootNode, 'children', _this2.treeData); - }; - - this.$watch('rootNode', updateRootNode, { - immediate: true - }); - this.$watch('treeData', updateRootNode, { - immediate: true - }); - }, - mounted: function mounted() { - var _this3 = this; - - // - this.treeId = hp.randString(); - this.$set(this.trees, this.treeId, this); - this.$once('hook:beforeDestroy', function () { - _this3.$delete(_this3.trees, _this3.treeId); - }); - }, - // beforeDestroy() {}, - // - mixPlugins: function mixPlugins(plugins) { - var MixedTree = { - name: 'Tree', - extends: Tree, - mixins: plugins, - mixPlugins: this.mixPlugins - }; - return MixedTree; - } -}; - -/* script */ -var __vue_script__ = Tree; -/* template */ - -/* style */ - -var __vue_inject_styles__ = undefined; -/* scoped */ - -var __vue_scope_id__ = undefined; -/* module identifier */ - -var __vue_module_identifier__ = undefined; -/* functional template */ - -var __vue_is_functional_template__ = undefined; -/* style inject */ - -/* style inject SSR */ - -/* style inject shadow dom */ - -var __vue_component__ = /*#__PURE__*/__vue_normalize__({}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, false, undefined, undefined, undefined); - -function ownKeys$1(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$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } -function foldAll(treeData) { - walkTreeData(treeData, function (childNode) { - Vue.set(childNode, '$folded', true); - }); -} -function unfoldAll(treeData) { - walkTreeData(treeData, function (childNode) { - Vue.set(childNode, '$folded', false); - }); -} -var fold = { - props: { - foldingTransitionName: { - type: String - }, - foldingTransition: {}, - foldAllAfterMounted: { - type: Boolean - } - }, - methods: { - fold: function fold(node, path) { - if (!node.$folded) { - this.$set(node, '$folded', true); - this.$emit('nodeFoldedChanged', node); - } - }, - unfold: function unfold(node, path) { - var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - opt = _objectSpread$1({ - foldOthers: false - }, opt); - - if (opt.foldOthers) { - this.foldAll(); - } - - if (node.$folded) { - this.$set(node, '$folded', false); - this.$emit('nodeFoldedChanged', node); - this.$emit('node-folded-changed', node); - } - }, - toggleFold: function toggleFold(node, path, opt) { - if (node.$folded) { - this.unfold(node, path, opt); - } else { - this.fold(node, path, opt); - } - }, - foldAll: function foldAll() { - var _this = this; - - this.walkTreeData(function (childNode) { - _this.fold(childNode); - }); - }, - unfoldAll: function unfoldAll() { - var _this2 = this; - - this.walkTreeData(function (childNode) { - _this2.unfold(childNode, { - unfoldParent: false - }); - }); - } - }, - mounted: function mounted() { - if (this.foldAllAfterMounted) { - this.foldAll(); - } - } -}; - -function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } -var check = { - props: {}, - methods: { - afterCheckChanged: function afterCheckChanged(node, path) { - var _this = this; - - // update parent - var nodes = this.getAllNodesByPath(path); - var reversedParents = nodes.slice(0, nodes.length - 1); - reversedParents.reverse(); - - var _iterator = _createForOfIteratorHelper(reversedParents), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var parent = _step.value; - this.$set(parent, '$checked', parent.children.every(function (child) { - return child.$checked; - })); - } // update children - - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (node.children && node.children.length > 0) { - walkTreeData(node.children, function (childNode) { - _this.$set(childNode, '$checked', node.$checked); - }); - } - }, - check: function check(node, path) { - this.$set(node, '$checked', true); - this.afterCheckChanged(node, path); - }, - uncheck: function uncheck(node, path) { - this.$set(node, '$checked', false); - this.afterCheckChanged(node, path); - }, - toggleCheck: function toggleCheck(node, path) { - this.$set(node, '$checked', !node.$checked); - this.afterCheckChanged(node, path); - } - } -}; - -function doDraggableDecision (_ref) { - var conditions = _ref.conditions, - doAction = _ref.doAction; - - // decision start ================================= - if (conditions['no closest'] === true) { - doAction('append to root'); - } else if (conditions['no closest'] === false) { - if (conditions['closest is top'] === true) { - if (conditions['on closest middle'] === true) { - doAction('insert before'); - } else if (conditions['on closest middle'] === false) { - if (conditions['at closest indent right'] === true) { - doAction('prepend'); - } else if (conditions['at closest indent right'] === false) { - if (conditions['closest is placeholder'] === true) { - doAction('insert after'); - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } - } - } else if (conditions['closest is top'] === false) { - if (conditions['on closest middle'] === true) { - if (conditions['at closest indent right'] === false) { - if (conditions['at closest left'] === false) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } else if (conditions['closest has next'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } else if (conditions['closest is placeholder'] === true) { - doAction('nothing'); - } - } else if (conditions['at closest left'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - doAction('nothing'); - } else if (conditions['no aboveBranch'] === false) { - doAction('after above'); - } - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } - } - } else if (conditions['at closest indent right'] === true) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - if (conditions['closest is top excluding placeholder'] === true) { - doAction('insert before'); - } else if (conditions['closest is top excluding placeholder'] === false) { - doAction('prepend'); - } - } - } else if (conditions['closest has next'] === false) { - doAction('prepend'); - } - } else if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - if (conditions['closest has prev'] === false) { - doAction('nothing'); - } else if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } - } else if (conditions['no aboveBranch'] === false) { - if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } else if (conditions['closest has prev'] === false) { - doAction('nothing'); - } - } - } - } - } else if (conditions['on closest middle'] === false) { - if (conditions['at closest indent right'] === false) { - if (conditions['at closest left'] === false) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } else if (conditions['closest is placeholder'] === true) { - doAction('nothing'); - } - } else if (conditions['at closest left'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === false) { - doAction('after above'); - } else if (conditions['no aboveBranch'] === true) { - doAction('nothing'); - } - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } else if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } - } - } else if (conditions['at closest indent right'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - if (conditions['closest has prev'] === false) { - doAction('nothing'); - } else if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } - } else if (conditions['no aboveBranch'] === false) { - if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } else if (conditions['closest has prev'] === false) { - doAction('nothing'); - } - } - } else if (conditions['closest is placeholder'] === false) { - doAction('prepend'); - } - } - } - } - } // decision end ================================= - -} - -function _createForOfIteratorHelper$1(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } - -function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function ownKeys$2(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$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function makeTreeDraggable(treeEl) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - options = _objectSpread$2(_objectSpread$2({}, options), {}, { - treeEl: treeEl - }); - - var _draggableHelper = draggableHelper(treeEl, { - triggerClassName: options.triggerClass, - triggerBySelf: options.triggerBySelf, - draggingClassName: options.draggingClass, - clone: options.cloneWhenDrag, - edgeScroll: options.edgeScroll, - edgeScrollTriggerMargin: options.edgeScrollTriggerMargin, - edgeScrollSpeed: options.edgeScrollSpeed, - edgeScrollTriggerMode: options.edgeScrollTriggerMode, - edgeScrollSpecifiedContainerX: options.edgeScrollSpecifiedContainerX, - edgeScrollSpecifiedContainerY: options.edgeScrollSpecifiedContainerY, - rtl: options.rtl, - preventTextSelection: options.preventTextSelection, - updateMovedElementStyleManually: true, - getMovedOrClonedElement: function getMovedOrClonedElement(directTriggerElement, store) { - // find closest branch from parents - var el = hp.findParent(store.triggerElement, function (el) { - return hp.hasClass(el, options.branchClass); - }, { - withSelf: true - }); - return el; - }, - beforeFirstMove: function beforeFirstMove(store, dhOptions) { - store.startTreeEl = treeEl; - store.dragBranchEl = store.movedElement; - store.startPath = options.getPathByBranchEl(store.movedOrClonedElement); - - if (options.beforeFirstMove && options.beforeFirstMove(store, dhOptions) === false) { - return false; - } - }, - beforeMove: function beforeMove(store, dhOptions) { - var updatePlaceholderIndent = function updatePlaceholderIndent() { - // set indent of placeholder - var placeholderPath = options.getPathByBranchEl(store.placeholder); - var placeholderNodeBack = store.placeholder.querySelector(".".concat(options.nodeBackClass)); - placeholderNodeBack.style[!options.rtl ? 'paddingLeft' : 'paddingRight'] = (placeholderPath.length - 1) * options.indent + 'px'; // remove tempChildren if empty - - if (store.tempChildren.children.length === 0) { - hp.removeEl(store.tempChildren); - } - }; // first move - // 第一次移动 - - - if (store.movedCount === 0) { - // create placeholder - // 创建占位元素 - var placeholder = hp.createElementFromHTML("\n
\n
\n
\n
\n
\n
\n ")); - hp.insertAfter(placeholder, store.movedOrClonedElement); - store.placeholder = placeholder; - options.afterPlaceholderCreated(store); // create a tree children el to use when can't get childrenEl - - var tempChildren = document.createElement('DIV'); - hp.addClass(tempChildren, options.childrenClass); - store.tempChildren = tempChildren; // update placeholder indent. update moved element style - - updatePlaceholderIndent(); - store.updateMovedElementStyle(); // skip first move - // 跳过第一次移动 - - return; - } // - - - store.updateMovedElementStyle(); // - - store.oneMoveStore = {}; // life cycle: one move - - var movingEl = store.movedElement; // branch - // find closest branch and hovering tree - - var _tree; - - var movingNode = movingEl.querySelector(".".concat(options.nodeClass)); // movingNodeOf and movingNodeRect are not always real. when RTL, there 'x' is top right. when draggingNodePositionMode is mouse, there x and y are mouse position. So don't calc them with their width or height. - // movingNodeOf 和 movingNodeRect并非一直如字面意义是movingNode真实坐标. RTL时, x坐标是右上角. draggingNodePositionMode是mouse时, x和y是鼠标坐标. - - var movingNodeOf = hp.getOffset(movingNode); - var movingNodeRect = hp.getBoundingClientRect(movingNode); - - if (options.draggingNodePositionMode === 'mouse') { - // use mouse position as dragging node position - var moveEvent = store.moveEvent; - movingNodeOf = { - x: moveEvent.pageX, - y: moveEvent.pageY - }; - movingNodeRect = { - x: moveEvent.clientX, - y: moveEvent.clientY - }; - } else if (options.rtl) { - movingNodeOf.x += movingNode.offsetWidth; - movingNodeRect.x += movingNode.offsetWidth; - } // find tree with elementsFromPoint - - - var found; - var firstElement; - - var _iterator = _createForOfIteratorHelper$1(hp.elementsFromPoint(movingNodeRect.x, movingNodeRect.y)), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var itemEl = _step.value; - - if (!firstElement) { - firstElement = itemEl; - } - - if (hp.hasClass(itemEl, options.treeClass)) { - found = itemEl; - break; - } - } // check if the found element is covered by other elements - - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (firstElement !== found && !hp.isDescendantOf(firstElement, found)) { - found = null; - } - - _tree = found; - - if (!_tree) { - // out of tree or tree is covered by other elements - return; - } // check if target tree right - - - if (options.filterTargetTree(_tree, store, dhOptions) === false) { - return; - } - - store.targetTreeEl = _tree; // info ======================================== - // life cycle: one move - - var info = { - tree: function tree() { - return _tree; - }, - root: function root() { - return info.tree.querySelector(".".concat(options.childrenClass)); - }, - closestNode: function closestNode() { - var nodes = []; // all visible nodes sort by y - - var walkToGetNodes = function walkToGetNodes(branch) { - // - if (branch !== info.tree) { - var node = branch.querySelector(".".concat(options.nodeClass)); - - if (node && !isElementHidden(node)) { - nodes.push(node); - } - } // - - - var childrenEl = branch.querySelector(".".concat(options.childrenClass)); - - if (childrenEl) { - for (var i = 0; i < childrenEl.children.length; i++) { - var child = childrenEl.children[i]; - - if (child !== movingEl && hp.hasClass(child, options.branchClass)) { - walkToGetNodes(child); - } - } - } - }; - - walkToGetNodes(info.tree); // - - if (nodes.length === 0) { - return; - } // - - - var found; - var t = hp.binarySearch(nodes, function (node) { - return hp.getOffset(node).y - movingNodeOf.y; - }, { - returnNearestIfNoHit: true - }); - - if (t.hit) { - found = t.value; - } else { - if (t.greater) { - found = nodes[t.index - 1] || t.value; - } else { - found = t.value; - } - } - - return found; - }, - closestNodeOffset: function closestNodeOffset() { - return hp.getOffset(info.closestNode); - }, - closestBranch: function closestBranch() { - return hp.findParent(info.closestNode, function (el) { - return hp.hasClass(el, options.branchClass); - }); - }, - closestNext: function closestNext() { - var next = info.closestBranch.nextSibling; - - while (next) { - if (next !== movingEl && hp.hasClass(next, options.branchClass) && !isElementHidden(next)) { - return next; - } - - next = next.nextSibling; - } - }, - closestPrev: function closestPrev() { - var prev = info.closestBranch.previousSibling; - - while (prev) { - if (prev !== movingEl && hp.hasClass(prev, options.branchClass) && !isElementHidden(prev)) { - return prev; - } - - prev = prev.previousSibling; - } - }, - aboveBranch: function aboveBranch() { - // find above from branch to root - // closestBranch must be placeholder - if (info.closestBranch !== store.placeholder) { - return; - } - - if (conditions['closest has next']) { - return; - } // find placeholder prev or parent - - - var cur = info.closestBranch; - var prev = cur.previousSibling; - var found; - - while (prev) { - if (prev !== movingEl && hp.hasClass(prev, options.branchClass) && !isElementHidden(prev)) { - cur = prev; - found = true; - break; - } - - prev = prev.previousSibling; - } - - if (!found) { - cur = hp.findParent(cur, function (el) { - return hp.hasClass(el, options.branchClass); - }); - } // - - - while (cur) { - var curNode = cur.querySelector(".".concat(options.nodeClass)); - - if (!options.rtl) { - if (hp.getOffset(curNode).x <= movingNodeOf.x) { - break; - } - } else { - if (hp.getOffset(curNode).x + curNode.offsetWidth >= movingNodeOf.x) { - break; - } - } - - var hasNextBranch = void 0; - var t = cur.nextSibling; - - while (t) { - if (t !== movingEl && t !== store.placeholder && hp.hasClass(t, options.branchClass) && !isElementHidden(t)) { - hasNextBranch = true; - break; - } - - t = t.nextSibling; - } - - if (hasNextBranch) { - break; - } - - var parent = hp.findParent(cur, function (el) { - return hp.hasClass(el, options.branchClass); - }); - - if (!parent) { - break; - } - - cur = parent; - } - - return cur; - } - }; // conditions ======================================== - // life cycle: one move - - var conditions = { - 'no closest': function noClosest() { - return !info.closestNode; - }, - 'closest is top': function closestIsTop() { - return info.closestBranch === hp.findNodeList(info.root.children, function (el) { - return el !== movingEl && !isElementHidden(el); - }); - }, - 'closest is top excluding placeholder': function closestIsTopExcludingPlaceholder() { - return info.closestBranch === hp.findNodeList(info.root.children, function (el) { - return el !== movingEl && el !== store.placeholder && !isElementHidden(el); - }); - }, - 'on closest middle': function onClosestMiddle() { - return movingNodeOf.y < info.closestNodeOffset.y + info.closestNode.offsetHeight / 2; - }, - 'at closest indent right': function atClosestIndentRight() { - return movingNodeOf.x > info.closestNodeOffset.x + options.indent; - }, - 'at closest left': function atClosestLeft() { - return movingNodeOf.x < info.closestNodeOffset.x; - }, - 'closest is placeholder': function closestIsPlaceholder() { - return info.closestBranch === store.placeholder; - }, - 'no aboveBranch': function noAboveBranch() { - return !info.aboveBranch; - }, - 'closest has next': function closestHasNext() { - return info.closestNext; - }, - 'closest has prev': function closestHasPrev() { - return info.closestPrev; - }, - 'closest has children excluding placeholder movingEl': function closestHasChildrenExcludingPlaceholderMovingEl() { - var childrenEl = info.closestBranch.querySelector(".".concat(options.childrenClass)); - - if (childrenEl) { - return hp.findNodeList(childrenEl.children, function (el) { - return el !== movingEl && el !== store.placeholder && !isElementHidden(el); - }); - } - } - }; // fix for rtl - - if (options.rtl) { - Object.assign(conditions, { - 'at closest indent right': function atClosestIndentRight() { - return movingNodeOf.x < info.closestNodeOffset.x + info.closestNode.offsetWidth - options.indent; - }, - // at indent left - 'at closest left': function atClosestLeft() { - return movingNodeOf.x > info.closestNodeOffset.x + info.closestNode.offsetWidth; - } // at right - - }); - } // convert conditions result to Boolean - - - Object.keys(conditions).forEach(function (key) { - var old = conditions[key]; - - conditions[key] = function () { - return Boolean(old.call(this)); - }; - }); // - - hp.attachCache(info, info); - hp.attachCache(conditions, conditions); - store.oneMoveStore.info = info; - store.oneMoveStore.conditions = conditions; // actions start ======================================== - - var doAction = function doAction(name) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - if (!store._doActionQueue) { - store._doActionQueue = Promise.resolve(); - } - - var queue = store._doActionQueue; - store._doActionQueue = queue.then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { - var actionRecords, action, r; - return _regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - // record tried actions in one move - if (!store.oneMoveStore.actionRecords) { - store.oneMoveStore.actionRecords = []; - } - - actionRecords = store.oneMoveStore.actionRecords; // - - action = actions[name]; - r = action.apply(void 0, args); - actionRecords.push(name); - _context.next = 7; - return r; - - case 7: - updatePlaceholderIndent(); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee); - }))); - }; - - var actions = { - 'nothing': function nothing() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { - return _regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - case "end": - return _context2.stop(); - } - } - }, _callee2); - }))(); - }, - // do nothing - 'append to root': function appendToRoot() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { - return _regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - // no closest branch, just append to root - if (options.isTargetTreeRootDroppable(store)) { - hp.appendTo(store.placeholder, info.root); - } - - case 1: - case "end": - return _context3.stop(); - } - } - }, _callee3); - }))(); - }, - 'insert before': function insertBefore() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { - return _regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - if (!options.isNodeParentDroppable(info.closestBranch, store.targetTreeEl)) { - _context4.next = 4; - break; - } - - hp.insertBefore(store.placeholder, info.closestBranch); - _context4.next = 5; - break; - - case 4: - return _context4.abrupt("return", secondCase(getParentBranchByEl(info.closestBranch))); - - case 5: - case "end": - return _context4.stop(); - } - } - }, _callee4); - }))(); - }, - 'insert after': function insertAfter() { - var _arguments = arguments; - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() { - var branch, moved, isFirstTriedAction; - return _regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - branch = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : info.closestBranch; - - if (!options.isNodeParentDroppable(branch, store.targetTreeEl)) { - _context5.next = 5; - break; - } - - hp.insertAfter(store.placeholder, branch); - _context5.next = 11; - break; - - case 5: - _context5.next = 7; - return secondCase(getParentBranchByEl(branch)); - - case 7: - moved = _context5.sent; - isFirstTriedAction = !store.oneMoveStore.actionRecords || store.oneMoveStore.actionRecords.length === 1; - - if (!(!moved && isFirstTriedAction)) { - _context5.next = 11; - break; - } - - return _context5.abrupt("return", thirdCase(branch)); - - case 11: - case "end": - return _context5.stop(); - } - } - }, _callee5); - }))(); - }, - prepend: function prepend() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() { - return _regeneratorRuntime.wrap(function _callee6$(_context6) { - while (1) { - switch (_context6.prev = _context6.next) { - case 0: - if (!(info.closestBranch === store.placeholder)) { - _context6.next = 2; - break; - } - - return _context6.abrupt("return"); - - case 2: - if (!(options.ifNodeFolded(info.closestBranch, store) && !options.unfoldWhenDragover)) { - _context6.next = 6; - break; - } - - return _context6.abrupt("return", doAction('insert after', info.closestBranch)); - - case 6: - if (!options.isNodeDroppable(info.closestBranch, store.targetTreeEl)) { - _context6.next = 11; - break; - } - - _context6.next = 9; - return tryUnfoldAndPrepend(info.closestBranch); - - case 9: - _context6.next = 12; - break; - - case 11: - return _context6.abrupt("return", secondCase(info.closestBranch)); - - case 12: - case "end": - return _context6.stop(); - } - } - }, _callee6); - }))(); - }, - 'after above': function afterAbove() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() { - return _regeneratorRuntime.wrap(function _callee7$(_context7) { - while (1) { - switch (_context7.prev = _context7.next) { - case 0: - if (!options.isNodeParentDroppable(info.aboveBranch, store.targetTreeEl)) { - _context7.next = 4; - break; - } - - hp.insertAfter(store.placeholder, info.aboveBranch); - _context7.next = 5; - break; - - case 4: - return _context7.abrupt("return", secondCase(getParentBranchByEl(info.aboveBranch))); - - case 5: - case "end": - return _context7.stop(); - } - } - }, _callee7); - }))(); - }, - 'append to prev': function appendToPrev() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { - var childrenEl; - return _regeneratorRuntime.wrap(function _callee8$(_context8) { - while (1) { - switch (_context8.prev = _context8.next) { - case 0: - if (!(info.closestPrev === store.placeholder)) { - _context8.next = 2; - break; - } - - return _context8.abrupt("return"); - - case 2: - if (!options.ifNodeFolded(info.closestPrev, store)) { - _context8.next = 6; - break; - } - - return _context8.abrupt("return", doAction('insert after', info.closestPrev)); - - case 6: - if (!options.isNodeDroppable(info.closestPrev, store.targetTreeEl)) { - _context8.next = 13; - break; - } - - _context8.next = 9; - return unfoldAndGetChildrenEl(info.closestPrev); - - case 9: - childrenEl = _context8.sent; - hp.appendTo(store.placeholder, childrenEl); - _context8.next = 14; - break; - - case 13: - return _context8.abrupt("return", secondCase(info.closestPrev)); - - case 14: - case "end": - return _context8.stop(); - } - } - }, _callee8); - }))(); - } - }; // second case for actions, when target position not droppable - // return true if moved - - var secondCase = /*#__PURE__*/function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(branchEl) { - var targetEl; - return _regeneratorRuntime.wrap(function _callee9$(_context9) { - while (1) { - switch (_context9.prev = _context9.next) { - case 0: - if (!branchEl) { - _context9.next = 5; - break; - } - - targetEl = options._findClosestDroppablePosition(branchEl, store.targetTreeEl); - - if (!targetEl) { - _context9.next = 5; - break; - } - - hp.insertAfter(store.placeholder, targetEl); - return _context9.abrupt("return", true); - - case 5: - case "end": - return _context9.stop(); - } - } - }, _callee9); - })); - - return function secondCase(_x) { - return _ref2.apply(this, arguments); - }; - }(); // when action is after, first case and second case invalid, try prepend - // 当操作是'after', 第一种第二种情况无效时, 尝试prepend - - - var thirdCase = /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(branchEl) { - return _regeneratorRuntime.wrap(function _callee10$(_context10) { - while (1) { - switch (_context10.prev = _context10.next) { - case 0: - if (!(!options.ifNodeFolded(branchEl, store) && options.isNodeDroppable(branchEl, store.targetTreeEl))) { - _context10.next = 3; - break; - } - - _context10.next = 3; - return tryUnfoldAndPrepend(branchEl); - - case 3: - case "end": - return _context10.stop(); - } - } - }, _callee10); - })); - - return function thirdCase(_x2) { - return _ref3.apply(this, arguments); - }; - }(); - - var unfoldAndGetChildrenEl = /*#__PURE__*/function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(branch) { - var childrenEl; - return _regeneratorRuntime.wrap(function _callee11$(_context11) { - while (1) { - switch (_context11.prev = _context11.next) { - case 0: - _context11.next = 2; - return options.unfoldTargetNodeByEl(branch, store); - - case 2: - childrenEl = branch.querySelector(".".concat(options.childrenClass)); - - if (!childrenEl) { - childrenEl = store.tempChildren; - hp.appendTo(childrenEl, branch); - } - - return _context11.abrupt("return", childrenEl); - - case 5: - case "end": - return _context11.stop(); - } - } - }, _callee11); - })); - - return function unfoldAndGetChildrenEl(_x3) { - return _ref4.apply(this, arguments); - }; - }(); - - var tryUnfoldAndPrepend = /*#__PURE__*/function () { - var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(branchEl) { - var func, oneMoveStore; - return _regeneratorRuntime.wrap(function _callee13$(_context13) { - while (1) { - switch (_context13.prev = _context13.next) { - case 0: - func = /*#__PURE__*/function () { - var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12() { - var childrenEl; - return _regeneratorRuntime.wrap(function _callee12$(_context12) { - while (1) { - switch (_context12.prev = _context12.next) { - case 0: - _context12.next = 2; - return unfoldAndGetChildrenEl(branchEl); - - case 2: - childrenEl = _context12.sent; - hp.prependTo(store.placeholder, childrenEl); - - case 4: - case "end": - return _context12.stop(); - } - } - }, _callee12); - })); - - return function func() { - return _ref6.apply(this, arguments); - }; - }(); - - if (!options.ifNodeFolded(branchEl, store)) { - _context13.next = 6; - break; - } - - // delay if node folded - oneMoveStore = store.oneMoveStore; - setTimeout(function () { - // check if expired - if (oneMoveStore === store.oneMoveStore) { - func(); - } - }, options.unfoldWhenDragoverDelay); - _context13.next = 8; - break; - - case 6: - _context13.next = 8; - return func(); - - case 8: - case "end": - return _context13.stop(); - } - } - }, _callee13); - })); - - return function tryUnfoldAndPrepend(_x4) { - return _ref5.apply(this, arguments); - }; - }(); // actions end ======================================== - - - doDraggableDecision({ - options: options, - event: store.moveEvent, - store: store, - opt: dhOptions, - info: info, - conditions: conditions, - actions: actions, - doAction: doAction - }); - }, - afterMove: function afterMove(store, dhOptions) { - options.afterMove && options.afterMove(store, dhOptions); - }, - beforeDrop: function () { - var _beforeDrop = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(store, dhOptions) { - var endEvent, movingEl, placeholder, tempChildren, movedCount, targetTreeEl, startTreeEl, maskTree, maskTree2, pathChanged, getTargetPath; - return _regeneratorRuntime.wrap(function _callee14$(_context14) { - while (1) { - switch (_context14.prev = _context14.next) { - case 0: - getTargetPath = function _getTargetPath() { - // example - // startPath placeholderPath - // [0] [1] - // [0] [1, 0] - // [3, 1] [3, 3] - // [3, 1] [3, 3, 5] - // above targetPaths should be [0], [0, 0] [3, 2] [3, 2, 5] - var startTree = store.startTree, - targetTree = store.targetTree, - startPath = store.startPath, - placeholderPath = store.placeholderPath; - var targetPath = placeholderPath.slice(0); - - if (options.cloneWhenDrag !== true) { - if (startTree === targetTree) { - if (startPath.length <= targetPath.length) { - var sw = startPath.slice(0, startPath.length - 1); // without end - - var tw = targetPath.slice(0, sw.length); // same length with sw - - if (sw.toString() === tw.toString()) { - var endIndex = sw.length; - - if (startPath[endIndex] < targetPath[endIndex]) { - targetPath[endIndex] -= 1; - } else if (startPath[endIndex] === targetPath[endIndex]) ; - } - } - } - } - - return targetPath; - }; - - endEvent = store.endEvent; - movingEl = store.movedElement; // branch - - placeholder = store.placeholder, tempChildren = store.tempChildren, movedCount = store.movedCount, targetTreeEl = store.targetTreeEl, startTreeEl = store.startTreeEl; // use mask tree to avoid flick caused by DOM update in short time - // 复制 targetTreeEl 作为遮罩, 避免短时间内更新DOM引起的闪烁 - - if (targetTreeEl) { - // No targetTreeEl mean no valid move. - // targetTreeEl不存在意味着没有有效移动. - // create mask tree - maskTree = targetTreeEl.cloneNode(true); - targetTreeEl.style.display = 'none'; - hp.insertAfter(maskTree, targetTreeEl); - - if (startTreeEl !== targetTreeEl) { - maskTree2 = startTreeEl.cloneNode(true); - startTreeEl.style.display = 'none'; - hp.insertAfter(maskTree2, startTreeEl); - } // - - - store.placeholderPath = options.getPathByBranchEl(placeholder); - store.targetPath = getTargetPath(); - pathChanged = targetTreeEl === startTreeEl && store.targetPath.toString() !== store.startPath.toString(); - store.pathChangePrevented = false; - - if (options.beforeDrop && options.beforeDrop(pathChanged, store, dhOptions) === false) { - pathChanged = false; - store.pathChangePrevented = false; - } - - store.pathChanged = pathChanged; - } // destroy placeholder and tempChildren - - - hp.removeEl(placeholder); - - if (tempChildren) { - hp.removeEl(tempChildren); - } - - store.updateMovedElementStyle(); // - - _context14.next = 10; - return options.afterDrop(store, dhOptions); - - case 10: - if (!maskTree) { - _context14.next = 16; - break; - } - - _context14.next = 13; - return hp.waitTime(0); - - case 13: - hp.removeEl(maskTree); - targetTreeEl.style.display = 'block'; - - if (maskTree2) { - hp.removeEl(maskTree2); - startTreeEl.style.display = 'block'; - } - - case 16: - case "end": - return _context14.stop(); - } - } - }, _callee14); - })); - - function beforeDrop(_x5, _x6) { - return _beforeDrop.apply(this, arguments); - } - - return beforeDrop; - }() - }), - destroy = _draggableHelper.destroy, - draggableHelperOptions = _draggableHelper.options; - - return { - destroy: destroy, - options: options, - optionsUpdated: optionsUpdated - }; - - function getParentBranchByEl(el) { - return hp.findParent(el, function (el) { - if (hp.hasClass(el, options.branchClass)) { - return true; - } - - if (hp.hasClass(el, options.rootClass)) { - return 'break'; - } - }); - } - - function optionsUpdated() { - Object.assign(draggableHelperOptions, { - triggerClassName: options.triggerClass, - triggerBySelf: options.triggerBySelf, - draggingClassName: options.draggingClass, - clone: options.cloneWhenDrag, - // edgeScroll - edgeScroll: options.edgeScroll, - edgeScrollTriggerMargin: options.edgeScrollTriggerMargin, - edgeScrollSpeed: options.edgeScrollSpeed, - edgeScrollTriggerMode: options.edgeScrollTriggerMode, - // - rtl: options.rtl, - preventTextSelection: options.preventTextSelection - }); - } -} - -function isElementHidden(el) { - return el.offsetWidth === 0 && el.offsetHeight === 0; -} - -function _createForOfIteratorHelper$2(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); } - -function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } -var treesStore = {}; -var script = { - props: { - triggerClass: { - type: [String, Array], - default: 'tree-node' - }, - triggerBySelf: { - type: Boolean - }, - draggable: { - type: [Boolean, Function], - default: true - }, - droppable: { - type: [Boolean, Function], - default: true - }, - eachDraggable: { - type: [Function] - }, - // type: [Boolean, Function] - eachDroppable: { - type: [Function] - }, - // type: [Boolean, Function] - ondragstart: { - type: Function - }, - ondragend: { - type: Function - }, - unfoldWhenDragover: { - type: Boolean, - default: true - }, - unfoldWhenDragoverDelay: { - type: Number, - default: 30 - }, - draggingNodePositionMode: { - type: String, - default: 'top_left_corner' - }, - // top_left_corner, mouse - edgeScroll: { - type: Boolean - }, - edgeScrollTriggerMargin: { - type: Number, - default: 50 - }, - edgeScrollSpeed: { - type: Number, - default: 0.35 - }, - edgeScrollTriggerMode: { - type: String, - default: 'top_left_corner' - }, - edgeScrollSpecifiedContainerX: {}, - // HTMLElement || ((store) => HTMLElement) - edgeScrollSpecifiedContainerY: {}, - // HTMLElement || ((store) => HTMLElement) - preventTextSelection: { - type: Boolean, - default: true - } - }, - // components: {}, - data: function data() { - return { - treesStore: treesStore - }; - }, - // computed: {}, - // watch: {}, - methods: { - _Draggable_unfoldTargetNodeByEl: function _Draggable_unfoldTargetNodeByEl(branchEl, store) { - var targetTree = store.targetTree; - var path = targetTree.getPathByBranchEl(branchEl); - var node = targetTree.getNodeByPath(path); - targetTree.unfold && targetTree.unfold(node, path); - return new Promise(function (resolve, reject) { - targetTree.$nextTick(function () { - resolve(); - }); - }); - }, - isNodeDraggable: function isNodeDraggable(node, path) { - var store = this.treesStore.store; - var allNodes = this.getAllNodesByPath(path); - allNodes.unshift(this.rootNode); - - var _iterator = _createForOfIteratorHelper$2(hp.iterateAll(allNodes, { - reverse: true - })), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _step$value = _step.value, - _node = _step$value.value, - index = _step$value.index; - var currentPath = path.slice(0, index + 1); - var draggableOpt = _node.$draggable !== undefined ? _node.$draggable : this.eachDraggable; - var draggable = hp.resolveValueOrGettter(draggableOpt, [currentPath, this, store]); - - if (draggable === undefined) { - continue; - } else { - return draggable; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return true; - }, - isNodeDroppable: function isNodeDroppable(node, path) { - var store = this.treesStore.store; - var allNodes = this.getAllNodesByPath(path); - allNodes.unshift(this.rootNode); - var droppableFinal, resolved; - - var _iterator2 = _createForOfIteratorHelper$2(hp.iterateAll(allNodes, { - reverse: true - })), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var _step2$value = _step2.value, - _node2 = _step2$value.value, - index = _step2$value.index; - var currentPath = path.slice(0, index + 1); - var droppableOpt = _node2.$droppable !== undefined ? _node2.$droppable : this.eachDroppable; - var droppable = hp.resolveValueOrGettter(droppableOpt, [currentPath, this, store]); - - if (droppable === undefined) { - continue; - } else { - droppableFinal = droppable; - resolved = true; - break; - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - - if (!resolved) { - droppableFinal = true; - } - - if (this._internal_hook_isNodeDroppable) { - return this._internal_hook_isNodeDroppable({ - droppableFinal: droppableFinal, - node: node, - path: path, - store: store - }); - } - - return droppableFinal; - }, - // override - getPathByBranchEl: function getPathByBranchEl(branchEl) { - var store = this.treesStore.store; - - var getAttrPath = function getAttrPath(el) { - var pathStr = el.getAttribute('data-tree-node-path'); - - if (pathStr) { - return pathStr.split(',').map(function (v) { - return parseInt(v); - }); - } - }; - - var path = getAttrPath(branchEl); - - if (path) { - return path; - } // placeholder path - - - var parentPath; - hp.findParent(branchEl, function (el) { - if (hp.hasClass(el, 'tree-root')) { - parentPath = []; - return true; - } - - if (hp.hasClass(el, 'tree-branch')) { - parentPath = getAttrPath(el); - return true; - } - }); - var index = 0; - - var _iterator3 = _createForOfIteratorHelper$2(hp.iterateAll(branchEl.parentElement.children)), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _step3$value = _step3.value, - el = _step3$value.value, - index2 = _step3$value.index; - - if (hp.hasClass(el, 'tree-branch') || hp.hasClass(el, 'tree-placeholder')) { - if (el === branchEl) { - break; - } - - index++; - } - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - return [].concat(_toConsumableArray(parentPath), [index]); - } - }, - // created() {}, - mounted: function mounted() { - var _this = this; - - var options = this._draggableOptions = { - indent: this.indent, - triggerClass: this.triggerClass, - triggerBySelf: this.triggerBySelf, - unfoldWhenDragover: this.unfoldWhenDragover, - unfoldWhenDragoverDelay: this.unfoldWhenDragoverDelay, - draggingNodePositionMode: this.draggingNodePositionMode, - cloneWhenDrag: this.cloneWhenDrag, - edgeScroll: this.edgeScroll, - edgeScrollTriggerMargin: this.edgeScrollTriggerMargin, - edgeScrollSpeed: this.edgeScrollSpeed, - edgeScrollTriggerMode: this.edgeScrollTriggerMode, - edgeScrollSpecifiedContainerX: this.edgeScrollSpecifiedContainerX, - edgeScrollSpecifiedContainerY: this.edgeScrollSpecifiedContainerY, - rtl: this.rtl, - preventTextSelection: this.preventTextSelection, - treeClass: 'he-tree', - rootClass: 'tree-root', - childrenClass: 'tree-children', - branchClass: 'tree-branch', - nodeClass: 'tree-node', - nodeBackClass: 'tree-node-back', - placeholderClass: 'tree-placeholder', - placeholderNodeBackClass: 'tree-placeholder-node-back', - placeholderNodeClass: 'tree-placeholder-node', - draggingClass: 'dragging', - placeholderId: "he_tree_drag_placeholder", - ifNodeFolded: function ifNodeFolded(branchEl, store) { - var targetTree = store.targetTree; - var node = targetTree.getNodeByBranchEl(branchEl); - return node.$folded; - }, - isTargetTreeRootDroppable: function isTargetTreeRootDroppable(store) { - var droppable = hp.resolveValueOrGettter(store.targetTree.rootNode.$droppable, [store.targetTree, store]); - - if (droppable !== undefined) { - return droppable; - } - - return true; - }, - unfoldTargetNodeByEl: function unfoldTargetNodeByEl() { - return _this._Draggable_unfoldTargetNodeByEl.apply(_this, arguments); - }, - isNodeParentDroppable: function isNodeParentDroppable(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var parentPath = hp.arrayWithoutEnd(path, 1); - var parent = tree.getNodeByPath(parentPath); - return tree.isNodeDroppable(parent, parentPath); - }, - isNodeDroppable: function isNodeDroppable(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var node = tree.getNodeByPath(path); - return tree.isNodeDroppable(node, path); - }, - _findClosestDroppablePosition: function _findClosestDroppablePosition(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var findPath = hp.arrayWithoutEnd(path, 1); - var cur = path; - - var _iterator4 = _createForOfIteratorHelper$2(tree.iteratePath(findPath, { - reverse: true - })), - _step4; - - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var _step4$value = _step4.value, - node = _step4$value.node, - _path = _step4$value.path; - - if (tree.isNodeDroppable(node, _path)) { - return tree.getBranchElByPath(cur); - } else { - cur = _path; - } - } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); - } - - if (tree.isNodeDroppable(_this.rootNode, [])) { - return tree.getBranchElByPath(cur); - } - }, - afterPlaceholderCreated: function afterPlaceholderCreated(store) { - store.startTree.$emit('afterPlaceholderCreated', store); - store.startTree.$emit('after-placeholder-created', store); - }, - getPathByBranchEl: function getPathByBranchEl(branchEl) { - return _this.getPathByBranchEl(branchEl); - }, - beforeFirstMove: function beforeFirstMove(store) { - _this.treesStore.store = store; - store.startTree = _this.getTreeVmByTreeEl(store.startTreeEl); - var draggable = hp.resolveValueOrGettter(store.startTree.draggable, [store.startTree, store]); - - if (!draggable) { - return false; - } - - var startTree = store.startTree, - dragBranchEl = store.dragBranchEl, - startPath = store.startPath; - store.dragNode = startTree.getNodeByPath(startPath); - - if (_this.cloneWhenDrag) { - store.dragNode = cloneTreeData(store.dragNode); - } - - if (!startTree.isNodeDraggable(store.dragNode, startPath)) { - return false; - } - - if (startTree.hasHook('ondragstart') && startTree.executeHook('ondragstart', [startTree, store]) === false) { - return false; - } - - store.startTree.$emit('before-first-move', store); - store.startTree.$emit('drag', store); - - _this.$root.$emit('he-tree-drag', store); - }, - filterTargetTree: function filterTargetTree(targetTreeEl, store) { - var targetTree = _this.getTreeVmByTreeEl(targetTreeEl); - - var startTree = store.startTree; - - if (startTree !== targetTree) { - if (_this._internal_hook_filterTargetTree) { - if (_this._internal_hook_filterTargetTree(targetTree, store) === false) { - return false; - } - } else { - return false; - } - } - - var targetTreeDroppable = hp.resolveValueOrGettter(targetTree.droppable, [targetTree, store]); - - if (!targetTreeDroppable) { - return false; - } - - store.targetTree = targetTree; - - if (!hp.resolveValueOrGettter(store.startTree === store.targetTree) && hp.resolveValueOrGettter(_this._Draggable_unfoldTargetNode, [false, _this.treeData]) !== _this.rootNode.children) { - return false; - } - }, - afterMove: function afterMove(store) { - store.startTree.$emit('after-move', store); - }, - beforeDrop: function beforeDrop(pathChanged, store) { - var targetTree = store.targetTree; - - if (targetTree.hasHook('ondragend') && targetTree.executeHook('ondragend', [targetTree, store]) === false) { - return false; - } - - _this.$root.$emit('he-tree-before-drop', store); - }, - afterDrop: function afterDrop(store, t) { - if (store.pathChanged) { - var startTree = store.startTree, - targetTree = store.targetTree, - startPath = store.startPath, - dragNode = store.dragNode; - var targetPath = store.targetPath; - - if (_this.cloneWhenDrag !== true) { - // remove from start position - var startParentPath = hp.arrayWithoutEnd(startPath, 1); - var startParent = startTree.getNodeByPath(startParentPath); - var startSiblings = startParentPath.length === 0 ? startTree.treeData : startParent.children; - var startIndex = hp.arrayLast(startPath); - startSiblings.splice(startIndex, 1); - } // insert to target position - - - var targetParentPath = hp.arrayWithoutEnd(targetPath, 1); - var targetParent = targetTree.getNodeByPath(targetParentPath); - var targetSiblings; - - if (targetParentPath.length === 0) { - targetSiblings = targetTree.treeData; - } else { - if (!targetParent.children) { - _this.$set(targetParent, 'children', []); - } - - targetSiblings = targetParent.children; - } - - var targetIndex = hp.arrayLast(targetPath); - targetSiblings.splice(targetIndex, 0, dragNode); // emit event - - startTree.$emit('input', startTree.treeData); - startTree.$emit('change', store); - targetTree.$emit('drop', store); - - _this.$root.$emit('he-tree-drop', store); - - if (targetTree !== startTree) { - targetTree.$emit('input', targetTree.treeData); - targetTree.$emit('change', store); - } - - return new Promise(function (resolve, reject) { - targetTree.$nextTick(function () { - resolve(); - }); - }); - } - } - }; - - var _makeTreeDraggable_obj = this._makeTreeDraggable_obj = makeTreeDraggable(this.$el, options); // watch props and update options - - - ['indent', 'triggerClass', 'triggerBySelf', 'unfoldWhenDragover', 'unfoldWhenDragoverDelay', 'draggingNodePositionMode', 'cloneWhenDrag', 'edgeScroll', 'edgeScrollTriggerMargin', 'edgeScrollSpeed', 'edgeScrollTriggerMode', 'edgeScrollSpecifiedContainerY', 'edgeScrollSpecifiedContainerY', 'rtl', 'preventTextSelection'].forEach(function (name) { - _this.$watch(name, function (value) { - _makeTreeDraggable_obj.options[name] = value; - - _makeTreeDraggable_obj.optionsUpdated(); - }); - }); - } -}; - -/* script */ -var __vue_script__$1 = script; -/* template */ - -/* style */ - -var __vue_inject_styles__$1 = undefined; -/* scoped */ - -var __vue_scope_id__$1 = undefined; -/* module identifier */ - -var __vue_module_identifier__$1 = undefined; -/* functional template */ - -var __vue_is_functional_template__$1 = undefined; -/* style inject */ - -/* style inject SSR */ - -/* style inject shadow dom */ - -var __vue_component__$1 = /*#__PURE__*/__vue_normalize__({}, __vue_inject_styles__$1, __vue_script__$1, __vue_scope_id__$1, __vue_is_functional_template__$1, __vue_module_identifier__$1, false, undefined, undefined, undefined); - -exports.Check = check; -exports.Draggable = __vue_component__$1; -exports.Fold = fold; -exports.Tree = __vue_component__; -exports.cloneTreeData = cloneTreeData; -exports.foldAll = foldAll; -exports.getPureTreeData = getPureTreeData; -exports.unfoldAll = unfoldAll; -exports.walkTreeData = walkTreeData; diff --git a/dist/he-tree-vue.css b/dist/he-tree-vue.css index b8d1ed6..39c6c67 100644 --- a/dist/he-tree-vue.css +++ b/dist/he-tree-vue.css @@ -1,345 +1,18 @@ - -.he-tree .tree-node{ - border: 1px solid #ccc; - margin-bottom: 5px; - padding: 5px; -} -.he-tree--hidden{ - display: none; +.vl-items { + overflow: hidden; + box-sizing: border-box; } -.he-tree--rtl{ + +.he-tree-rtl { direction: rtl; } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/* .he-tree .tree-placeholder{ -} */ -.he-tree .tree-placeholder-node{ +.he-tree .tree-placeholder { background: #ddf2f9; border: 1px dashed #00d9ff; height: 20px; } -.he-tree .dragging .tree-node-back:hover{ +.he-tree .dragging .tree-node:hover { background-color: inherit; } diff --git a/dist/he-tree-vue.esm.js b/dist/he-tree-vue.esm.js deleted file mode 100644 index 2cb7b3d..0000000 --- a/dist/he-tree-vue.esm.js +++ /dev/null @@ -1,2061 +0,0 @@ -/*! - * he-tree-vue v2.0.11.beta.3 - * (c) phphe (https://github.com/phphe) - * Homepage: https://he-tree-vue.phphe.com - * Released under the MIT License. - */ -import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray'; -import _defineProperty from '@babel/runtime/helpers/defineProperty'; -import { TreeData, randString, findParent, hasClass, createElementFromHTML, insertAfter, addClass, getOffset, getBoundingClientRect, elementsFromPoint, isDescendantOf, attachCache, removeEl, binarySearch, findNodeList, appendTo, insertBefore, prependTo, waitTime, iterateAll, resolveValueOrGettter, arrayWithoutEnd, arrayLast } from 'helper-js'; -import { updatablePropsEvenUnbound, hookHelper } from 'vue-functions'; -import __vue_normalize__ from 'vue-runtime-helpers/dist/normalize-component.mjs'; -import Vue from 'vue'; -import _regeneratorRuntime from '@babel/runtime/regenerator'; -import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator'; -import draggableHelper from 'draggable-helper'; - -function cloneTreeData(treeData, opt) { - return new TreeData(treeData).clone(opt); -} -function walkTreeData(treeData, handler, opt) { - return new TreeData(treeData).walk(handler, opt); -} -function getPureTreeData(treeData) { - var opt = { - afterNodeCreated: function afterNodeCreated(newNode) { - Object.keys(newNode).forEach(function (key) { - if (key[0] === '$') { - delete newNode[key]; - } - }); - } - }; - return cloneTreeData(treeData, opt); -} - -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) { _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; } - -var template = function template(h) { - var _this = this; - - // convert undefined to empty str - var noUndefined = function noUndefined(str) { - return str ? str : ''; - }; // tree tpl, to render recursively - - - var childrenListTpl = function childrenListTpl(nodes, parent, parentPath) { - var indentStyle = _defineProperty({}, !_this.rtl ? 'paddingLeft' : 'paddingRight', parentPath.length * _this.indent + 'px'); - - var branchTpl = function branchTpl(node, index) { - var path = [].concat(_toConsumableArray(parentPath), [index]); - var transitionComponent = _this.foldingTransition || 'transition'; - - var slotDefault = function slotDefault() { - var original = function original() { - if (_this.$scopedSlots.default) { - return _this.$scopedSlots.default({ - node: node, - index: index, - path: path, - tree: _this - }); - } else if (_this.$slots.default) { - return _this.$slots.default; - } else { - return node.text; - } - }; - - if (_this.overrideSlotDefault) { - return _this.overrideSlotDefault({ - node: node, - index: index, - path: path, - tree: _this - }, original); - } else { - return original(); - } - }; - - var nodebackStyle = indentStyle; - - if (node.$nodeBackStyle) { - nodebackStyle = _objectSpread(_objectSpread({}, nodebackStyle), node.$nodeBackStyle); - } - - return h("div", { - "class": "tree-branch ".concat(noUndefined(node.$branchClass), " ").concat(noUndefined(node.$hidden && 'he-tree--hidden')), - "style": node.$branchStyle || {}, - "attrs": { - "data-tree-node-path": path.join(',') - } - }, [h("div", { - "class": "tree-node-back ".concat(noUndefined(node.$nodeBackClass)), - "style": nodebackStyle || {} - }, [h("div", { - "class": "tree-node ".concat(noUndefined(node.$nodeClass)), - "style": node.$nodeStyle || {} - }, [slotDefault()])]), (node.children && node.children.length) > 0 && h(transitionComponent, { - "attrs": { - "name": _this.$props.foldingTransitionName - } - }, [!node.$folded && childrenListTpl(node.children, node, path)])]); - }; - - return h("div", { - "class": "tree-children ".concat(noUndefined(parent === _this.rootNode && 'tree-root'), " ").concat(noUndefined(parent.$childrenClass)), - "style": parent.$childrenStyle || {} - }, [nodes.map(branchTpl)]); - }; - - return h("div", { - "class": "he-tree ".concat(this.treeClass, " ").concat(noUndefined(this.rtl && 'he-tree--rtl')), - "attrs": { - "data-tree-id": this.treeId - } - }, [this.blockHeader && this.blockHeader(), childrenListTpl(this.rootNode.children, this.rootNode, []), this.blockFooter && this.blockFooter()]); -}; - -var trees = {}; -var Tree = { - render: template, - mixins: [updatablePropsEvenUnbound({ - value: { - $localName: 'treeData', - required: true - } - }), hookHelper], - props: { - indent: { - type: Number, - default: 20 - }, - rtl: { - type: Boolean - }, - rootNode: { - default: function _default(is) { - return {}; - } - } - }, - // components: {}, - data: function data() { - return { - trees: trees, - treeClass: '', - treeId: randString() - }; - }, - // computed: {}, - watch: { - treeData: { - immediate: true, - handler: function handler(treeData) { - this._TreeDataHelper = new TreeData(this.treeData); - } - } - }, - methods: { - iteratePath: function iteratePath(path, opt) { - return this._TreeDataHelper.iteratePath(path, opt); - }, - getTreeVmByTreeEl: function getTreeVmByTreeEl(treeEl) { - return this.trees[treeEl.getAttribute('data-tree-id')]; - }, - getAllNodesByPath: function getAllNodesByPath(path) { - return this._TreeDataHelper.getAllNodes(path); - }, - getNodeByPath: function getNodeByPath(path) { - return this._TreeDataHelper.getNode(path); - }, - getPathByBranchEl: function getPathByBranchEl(branchEl) { - return branchEl.getAttribute('data-tree-node-path').split(',').map(function (v) { - return parseInt(v); - }); - }, - getBranchElByPath: function getBranchElByPath(path) { - return this.$el.querySelector("[data-tree-node-path='".concat(path.join(','), "']")); - }, - getNodeByBranchEl: function getNodeByBranchEl(branchEl) { - return this.getNodeByPath(this.getPathByBranchEl(branchEl)); - }, - getNodeParentByPath: function getNodeParentByPath(path) { - return this._TreeDataHelper.getNodeParent(path); - }, - removeNodeByPath: function removeNodeByPath(path) { - return this._TreeDataHelper.removeNode(path); - }, - walkTreeData: function walkTreeData$1(handler, opt) { - return walkTreeData(this.treeData, handler, opt); - }, - cloneTreeData: function cloneTreeData$1(opt) { - return cloneTreeData(this.treeData, opt); - }, - // return cloned new tree data without property witch starts with `$` - getPureTreeData: function getPureTreeData$1() { - return getPureTreeData(this.treeData); - } - }, - created: function created() { - var _this2 = this; - - // - var updateRootNode = function updateRootNode() { - _this2.$set(_this2.rootNode, 'children', _this2.treeData); - }; - - this.$watch('rootNode', updateRootNode, { - immediate: true - }); - this.$watch('treeData', updateRootNode, { - immediate: true - }); - }, - mounted: function mounted() { - var _this3 = this; - - // - this.treeId = randString(); - this.$set(this.trees, this.treeId, this); - this.$once('hook:beforeDestroy', function () { - _this3.$delete(_this3.trees, _this3.treeId); - }); - }, - // beforeDestroy() {}, - // - mixPlugins: function mixPlugins(plugins) { - var MixedTree = { - name: 'Tree', - extends: Tree, - mixins: plugins, - mixPlugins: this.mixPlugins - }; - return MixedTree; - } -}; - -/* script */ -var __vue_script__ = Tree; -/* template */ - -/* style */ - -var __vue_inject_styles__ = undefined; -/* scoped */ - -var __vue_scope_id__ = undefined; -/* module identifier */ - -var __vue_module_identifier__ = undefined; -/* functional template */ - -var __vue_is_functional_template__ = undefined; -/* style inject */ - -/* style inject SSR */ - -/* style inject shadow dom */ - -var __vue_component__ = /*#__PURE__*/__vue_normalize__({}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, false, undefined, undefined, undefined); - -function ownKeys$1(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$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } -function foldAll(treeData) { - walkTreeData(treeData, function (childNode) { - Vue.set(childNode, '$folded', true); - }); -} -function unfoldAll(treeData) { - walkTreeData(treeData, function (childNode) { - Vue.set(childNode, '$folded', false); - }); -} -var fold = { - props: { - foldingTransitionName: { - type: String - }, - foldingTransition: {}, - foldAllAfterMounted: { - type: Boolean - } - }, - methods: { - fold: function fold(node, path) { - if (!node.$folded) { - this.$set(node, '$folded', true); - this.$emit('nodeFoldedChanged', node); - } - }, - unfold: function unfold(node, path) { - var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - opt = _objectSpread$1({ - foldOthers: false - }, opt); - - if (opt.foldOthers) { - this.foldAll(); - } - - if (node.$folded) { - this.$set(node, '$folded', false); - this.$emit('nodeFoldedChanged', node); - this.$emit('node-folded-changed', node); - } - }, - toggleFold: function toggleFold(node, path, opt) { - if (node.$folded) { - this.unfold(node, path, opt); - } else { - this.fold(node, path, opt); - } - }, - foldAll: function foldAll() { - var _this = this; - - this.walkTreeData(function (childNode) { - _this.fold(childNode); - }); - }, - unfoldAll: function unfoldAll() { - var _this2 = this; - - this.walkTreeData(function (childNode) { - _this2.unfold(childNode, { - unfoldParent: false - }); - }); - } - }, - mounted: function mounted() { - if (this.foldAllAfterMounted) { - this.foldAll(); - } - } -}; - -function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } -var check = { - props: {}, - methods: { - afterCheckChanged: function afterCheckChanged(node, path) { - var _this = this; - - // update parent - var nodes = this.getAllNodesByPath(path); - var reversedParents = nodes.slice(0, nodes.length - 1); - reversedParents.reverse(); - - var _iterator = _createForOfIteratorHelper(reversedParents), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var parent = _step.value; - this.$set(parent, '$checked', parent.children.every(function (child) { - return child.$checked; - })); - } // update children - - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (node.children && node.children.length > 0) { - walkTreeData(node.children, function (childNode) { - _this.$set(childNode, '$checked', node.$checked); - }); - } - }, - check: function check(node, path) { - this.$set(node, '$checked', true); - this.afterCheckChanged(node, path); - }, - uncheck: function uncheck(node, path) { - this.$set(node, '$checked', false); - this.afterCheckChanged(node, path); - }, - toggleCheck: function toggleCheck(node, path) { - this.$set(node, '$checked', !node.$checked); - this.afterCheckChanged(node, path); - } - } -}; - -function doDraggableDecision (_ref) { - var conditions = _ref.conditions, - doAction = _ref.doAction; - - // decision start ================================= - if (conditions['no closest'] === true) { - doAction('append to root'); - } else if (conditions['no closest'] === false) { - if (conditions['closest is top'] === true) { - if (conditions['on closest middle'] === true) { - doAction('insert before'); - } else if (conditions['on closest middle'] === false) { - if (conditions['at closest indent right'] === true) { - doAction('prepend'); - } else if (conditions['at closest indent right'] === false) { - if (conditions['closest is placeholder'] === true) { - doAction('insert after'); - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } - } - } else if (conditions['closest is top'] === false) { - if (conditions['on closest middle'] === true) { - if (conditions['at closest indent right'] === false) { - if (conditions['at closest left'] === false) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } else if (conditions['closest has next'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } else if (conditions['closest is placeholder'] === true) { - doAction('nothing'); - } - } else if (conditions['at closest left'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - doAction('nothing'); - } else if (conditions['no aboveBranch'] === false) { - doAction('after above'); - } - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } - } - } else if (conditions['at closest indent right'] === true) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - if (conditions['closest is top excluding placeholder'] === true) { - doAction('insert before'); - } else if (conditions['closest is top excluding placeholder'] === false) { - doAction('prepend'); - } - } - } else if (conditions['closest has next'] === false) { - doAction('prepend'); - } - } else if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - if (conditions['closest has prev'] === false) { - doAction('nothing'); - } else if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } - } else if (conditions['no aboveBranch'] === false) { - if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } else if (conditions['closest has prev'] === false) { - doAction('nothing'); - } - } - } - } - } else if (conditions['on closest middle'] === false) { - if (conditions['at closest indent right'] === false) { - if (conditions['at closest left'] === false) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } else if (conditions['closest is placeholder'] === true) { - doAction('nothing'); - } - } else if (conditions['at closest left'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === false) { - doAction('after above'); - } else if (conditions['no aboveBranch'] === true) { - doAction('nothing'); - } - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } else if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } - } - } else if (conditions['at closest indent right'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - if (conditions['closest has prev'] === false) { - doAction('nothing'); - } else if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } - } else if (conditions['no aboveBranch'] === false) { - if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } else if (conditions['closest has prev'] === false) { - doAction('nothing'); - } - } - } else if (conditions['closest is placeholder'] === false) { - doAction('prepend'); - } - } - } - } - } // decision end ================================= - -} - -function _createForOfIteratorHelper$1(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } - -function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function ownKeys$2(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$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function makeTreeDraggable(treeEl) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - options = _objectSpread$2(_objectSpread$2({}, options), {}, { - treeEl: treeEl - }); - - var _draggableHelper = draggableHelper(treeEl, { - triggerClassName: options.triggerClass, - triggerBySelf: options.triggerBySelf, - draggingClassName: options.draggingClass, - clone: options.cloneWhenDrag, - edgeScroll: options.edgeScroll, - edgeScrollTriggerMargin: options.edgeScrollTriggerMargin, - edgeScrollSpeed: options.edgeScrollSpeed, - edgeScrollTriggerMode: options.edgeScrollTriggerMode, - edgeScrollSpecifiedContainerX: options.edgeScrollSpecifiedContainerX, - edgeScrollSpecifiedContainerY: options.edgeScrollSpecifiedContainerY, - rtl: options.rtl, - preventTextSelection: options.preventTextSelection, - updateMovedElementStyleManually: true, - getMovedOrClonedElement: function getMovedOrClonedElement(directTriggerElement, store) { - // find closest branch from parents - var el = findParent(store.triggerElement, function (el) { - return hasClass(el, options.branchClass); - }, { - withSelf: true - }); - return el; - }, - beforeFirstMove: function beforeFirstMove(store, dhOptions) { - store.startTreeEl = treeEl; - store.dragBranchEl = store.movedElement; - store.startPath = options.getPathByBranchEl(store.movedOrClonedElement); - - if (options.beforeFirstMove && options.beforeFirstMove(store, dhOptions) === false) { - return false; - } - }, - beforeMove: function beforeMove(store, dhOptions) { - var updatePlaceholderIndent = function updatePlaceholderIndent() { - // set indent of placeholder - var placeholderPath = options.getPathByBranchEl(store.placeholder); - var placeholderNodeBack = store.placeholder.querySelector(".".concat(options.nodeBackClass)); - placeholderNodeBack.style[!options.rtl ? 'paddingLeft' : 'paddingRight'] = (placeholderPath.length - 1) * options.indent + 'px'; // remove tempChildren if empty - - if (store.tempChildren.children.length === 0) { - removeEl(store.tempChildren); - } - }; // first move - // 第一次移动 - - - if (store.movedCount === 0) { - // create placeholder - // 创建占位元素 - var placeholder = createElementFromHTML("\n
\n
\n
\n
\n
\n
\n ")); - insertAfter(placeholder, store.movedOrClonedElement); - store.placeholder = placeholder; - options.afterPlaceholderCreated(store); // create a tree children el to use when can't get childrenEl - - var tempChildren = document.createElement('DIV'); - addClass(tempChildren, options.childrenClass); - store.tempChildren = tempChildren; // update placeholder indent. update moved element style - - updatePlaceholderIndent(); - store.updateMovedElementStyle(); // skip first move - // 跳过第一次移动 - - return; - } // - - - store.updateMovedElementStyle(); // - - store.oneMoveStore = {}; // life cycle: one move - - var movingEl = store.movedElement; // branch - // find closest branch and hovering tree - - var _tree; - - var movingNode = movingEl.querySelector(".".concat(options.nodeClass)); // movingNodeOf and movingNodeRect are not always real. when RTL, there 'x' is top right. when draggingNodePositionMode is mouse, there x and y are mouse position. So don't calc them with their width or height. - // movingNodeOf 和 movingNodeRect并非一直如字面意义是movingNode真实坐标. RTL时, x坐标是右上角. draggingNodePositionMode是mouse时, x和y是鼠标坐标. - - var movingNodeOf = getOffset(movingNode); - var movingNodeRect = getBoundingClientRect(movingNode); - - if (options.draggingNodePositionMode === 'mouse') { - // use mouse position as dragging node position - var moveEvent = store.moveEvent; - movingNodeOf = { - x: moveEvent.pageX, - y: moveEvent.pageY - }; - movingNodeRect = { - x: moveEvent.clientX, - y: moveEvent.clientY - }; - } else if (options.rtl) { - movingNodeOf.x += movingNode.offsetWidth; - movingNodeRect.x += movingNode.offsetWidth; - } // find tree with elementsFromPoint - - - var found; - var firstElement; - - var _iterator = _createForOfIteratorHelper$1(elementsFromPoint(movingNodeRect.x, movingNodeRect.y)), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var itemEl = _step.value; - - if (!firstElement) { - firstElement = itemEl; - } - - if (hasClass(itemEl, options.treeClass)) { - found = itemEl; - break; - } - } // check if the found element is covered by other elements - - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (firstElement !== found && !isDescendantOf(firstElement, found)) { - found = null; - } - - _tree = found; - - if (!_tree) { - // out of tree or tree is covered by other elements - return; - } // check if target tree right - - - if (options.filterTargetTree(_tree, store, dhOptions) === false) { - return; - } - - store.targetTreeEl = _tree; // info ======================================== - // life cycle: one move - - var info = { - tree: function tree() { - return _tree; - }, - root: function root() { - return info.tree.querySelector(".".concat(options.childrenClass)); - }, - closestNode: function closestNode() { - var nodes = []; // all visible nodes sort by y - - var walkToGetNodes = function walkToGetNodes(branch) { - // - if (branch !== info.tree) { - var node = branch.querySelector(".".concat(options.nodeClass)); - - if (node && !isElementHidden(node)) { - nodes.push(node); - } - } // - - - var childrenEl = branch.querySelector(".".concat(options.childrenClass)); - - if (childrenEl) { - for (var i = 0; i < childrenEl.children.length; i++) { - var child = childrenEl.children[i]; - - if (child !== movingEl && hasClass(child, options.branchClass)) { - walkToGetNodes(child); - } - } - } - }; - - walkToGetNodes(info.tree); // - - if (nodes.length === 0) { - return; - } // - - - var found; - var t = binarySearch(nodes, function (node) { - return getOffset(node).y - movingNodeOf.y; - }, { - returnNearestIfNoHit: true - }); - - if (t.hit) { - found = t.value; - } else { - if (t.greater) { - found = nodes[t.index - 1] || t.value; - } else { - found = t.value; - } - } - - return found; - }, - closestNodeOffset: function closestNodeOffset() { - return getOffset(info.closestNode); - }, - closestBranch: function closestBranch() { - return findParent(info.closestNode, function (el) { - return hasClass(el, options.branchClass); - }); - }, - closestNext: function closestNext() { - var next = info.closestBranch.nextSibling; - - while (next) { - if (next !== movingEl && hasClass(next, options.branchClass) && !isElementHidden(next)) { - return next; - } - - next = next.nextSibling; - } - }, - closestPrev: function closestPrev() { - var prev = info.closestBranch.previousSibling; - - while (prev) { - if (prev !== movingEl && hasClass(prev, options.branchClass) && !isElementHidden(prev)) { - return prev; - } - - prev = prev.previousSibling; - } - }, - aboveBranch: function aboveBranch() { - // find above from branch to root - // closestBranch must be placeholder - if (info.closestBranch !== store.placeholder) { - return; - } - - if (conditions['closest has next']) { - return; - } // find placeholder prev or parent - - - var cur = info.closestBranch; - var prev = cur.previousSibling; - var found; - - while (prev) { - if (prev !== movingEl && hasClass(prev, options.branchClass) && !isElementHidden(prev)) { - cur = prev; - found = true; - break; - } - - prev = prev.previousSibling; - } - - if (!found) { - cur = findParent(cur, function (el) { - return hasClass(el, options.branchClass); - }); - } // - - - while (cur) { - var curNode = cur.querySelector(".".concat(options.nodeClass)); - - if (!options.rtl) { - if (getOffset(curNode).x <= movingNodeOf.x) { - break; - } - } else { - if (getOffset(curNode).x + curNode.offsetWidth >= movingNodeOf.x) { - break; - } - } - - var hasNextBranch = void 0; - var t = cur.nextSibling; - - while (t) { - if (t !== movingEl && t !== store.placeholder && hasClass(t, options.branchClass) && !isElementHidden(t)) { - hasNextBranch = true; - break; - } - - t = t.nextSibling; - } - - if (hasNextBranch) { - break; - } - - var parent = findParent(cur, function (el) { - return hasClass(el, options.branchClass); - }); - - if (!parent) { - break; - } - - cur = parent; - } - - return cur; - } - }; // conditions ======================================== - // life cycle: one move - - var conditions = { - 'no closest': function noClosest() { - return !info.closestNode; - }, - 'closest is top': function closestIsTop() { - return info.closestBranch === findNodeList(info.root.children, function (el) { - return el !== movingEl && !isElementHidden(el); - }); - }, - 'closest is top excluding placeholder': function closestIsTopExcludingPlaceholder() { - return info.closestBranch === findNodeList(info.root.children, function (el) { - return el !== movingEl && el !== store.placeholder && !isElementHidden(el); - }); - }, - 'on closest middle': function onClosestMiddle() { - return movingNodeOf.y < info.closestNodeOffset.y + info.closestNode.offsetHeight / 2; - }, - 'at closest indent right': function atClosestIndentRight() { - return movingNodeOf.x > info.closestNodeOffset.x + options.indent; - }, - 'at closest left': function atClosestLeft() { - return movingNodeOf.x < info.closestNodeOffset.x; - }, - 'closest is placeholder': function closestIsPlaceholder() { - return info.closestBranch === store.placeholder; - }, - 'no aboveBranch': function noAboveBranch() { - return !info.aboveBranch; - }, - 'closest has next': function closestHasNext() { - return info.closestNext; - }, - 'closest has prev': function closestHasPrev() { - return info.closestPrev; - }, - 'closest has children excluding placeholder movingEl': function closestHasChildrenExcludingPlaceholderMovingEl() { - var childrenEl = info.closestBranch.querySelector(".".concat(options.childrenClass)); - - if (childrenEl) { - return findNodeList(childrenEl.children, function (el) { - return el !== movingEl && el !== store.placeholder && !isElementHidden(el); - }); - } - } - }; // fix for rtl - - if (options.rtl) { - Object.assign(conditions, { - 'at closest indent right': function atClosestIndentRight() { - return movingNodeOf.x < info.closestNodeOffset.x + info.closestNode.offsetWidth - options.indent; - }, - // at indent left - 'at closest left': function atClosestLeft() { - return movingNodeOf.x > info.closestNodeOffset.x + info.closestNode.offsetWidth; - } // at right - - }); - } // convert conditions result to Boolean - - - Object.keys(conditions).forEach(function (key) { - var old = conditions[key]; - - conditions[key] = function () { - return Boolean(old.call(this)); - }; - }); // - - attachCache(info, info); - attachCache(conditions, conditions); - store.oneMoveStore.info = info; - store.oneMoveStore.conditions = conditions; // actions start ======================================== - - var doAction = function doAction(name) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - if (!store._doActionQueue) { - store._doActionQueue = Promise.resolve(); - } - - var queue = store._doActionQueue; - store._doActionQueue = queue.then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { - var actionRecords, action, r; - return _regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - // record tried actions in one move - if (!store.oneMoveStore.actionRecords) { - store.oneMoveStore.actionRecords = []; - } - - actionRecords = store.oneMoveStore.actionRecords; // - - action = actions[name]; - r = action.apply(void 0, args); - actionRecords.push(name); - _context.next = 7; - return r; - - case 7: - updatePlaceholderIndent(); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee); - }))); - }; - - var actions = { - 'nothing': function nothing() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { - return _regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - case "end": - return _context2.stop(); - } - } - }, _callee2); - }))(); - }, - // do nothing - 'append to root': function appendToRoot() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { - return _regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - // no closest branch, just append to root - if (options.isTargetTreeRootDroppable(store)) { - appendTo(store.placeholder, info.root); - } - - case 1: - case "end": - return _context3.stop(); - } - } - }, _callee3); - }))(); - }, - 'insert before': function insertBefore$1() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { - return _regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - if (!options.isNodeParentDroppable(info.closestBranch, store.targetTreeEl)) { - _context4.next = 4; - break; - } - - insertBefore(store.placeholder, info.closestBranch); - _context4.next = 5; - break; - - case 4: - return _context4.abrupt("return", secondCase(getParentBranchByEl(info.closestBranch))); - - case 5: - case "end": - return _context4.stop(); - } - } - }, _callee4); - }))(); - }, - 'insert after': function insertAfter$1() { - var _arguments = arguments; - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() { - var branch, moved, isFirstTriedAction; - return _regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - branch = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : info.closestBranch; - - if (!options.isNodeParentDroppable(branch, store.targetTreeEl)) { - _context5.next = 5; - break; - } - - insertAfter(store.placeholder, branch); - _context5.next = 11; - break; - - case 5: - _context5.next = 7; - return secondCase(getParentBranchByEl(branch)); - - case 7: - moved = _context5.sent; - isFirstTriedAction = !store.oneMoveStore.actionRecords || store.oneMoveStore.actionRecords.length === 1; - - if (!(!moved && isFirstTriedAction)) { - _context5.next = 11; - break; - } - - return _context5.abrupt("return", thirdCase(branch)); - - case 11: - case "end": - return _context5.stop(); - } - } - }, _callee5); - }))(); - }, - prepend: function prepend() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() { - return _regeneratorRuntime.wrap(function _callee6$(_context6) { - while (1) { - switch (_context6.prev = _context6.next) { - case 0: - if (!(info.closestBranch === store.placeholder)) { - _context6.next = 2; - break; - } - - return _context6.abrupt("return"); - - case 2: - if (!(options.ifNodeFolded(info.closestBranch, store) && !options.unfoldWhenDragover)) { - _context6.next = 6; - break; - } - - return _context6.abrupt("return", doAction('insert after', info.closestBranch)); - - case 6: - if (!options.isNodeDroppable(info.closestBranch, store.targetTreeEl)) { - _context6.next = 11; - break; - } - - _context6.next = 9; - return tryUnfoldAndPrepend(info.closestBranch); - - case 9: - _context6.next = 12; - break; - - case 11: - return _context6.abrupt("return", secondCase(info.closestBranch)); - - case 12: - case "end": - return _context6.stop(); - } - } - }, _callee6); - }))(); - }, - 'after above': function afterAbove() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() { - return _regeneratorRuntime.wrap(function _callee7$(_context7) { - while (1) { - switch (_context7.prev = _context7.next) { - case 0: - if (!options.isNodeParentDroppable(info.aboveBranch, store.targetTreeEl)) { - _context7.next = 4; - break; - } - - insertAfter(store.placeholder, info.aboveBranch); - _context7.next = 5; - break; - - case 4: - return _context7.abrupt("return", secondCase(getParentBranchByEl(info.aboveBranch))); - - case 5: - case "end": - return _context7.stop(); - } - } - }, _callee7); - }))(); - }, - 'append to prev': function appendToPrev() { - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { - var childrenEl; - return _regeneratorRuntime.wrap(function _callee8$(_context8) { - while (1) { - switch (_context8.prev = _context8.next) { - case 0: - if (!(info.closestPrev === store.placeholder)) { - _context8.next = 2; - break; - } - - return _context8.abrupt("return"); - - case 2: - if (!options.ifNodeFolded(info.closestPrev, store)) { - _context8.next = 6; - break; - } - - return _context8.abrupt("return", doAction('insert after', info.closestPrev)); - - case 6: - if (!options.isNodeDroppable(info.closestPrev, store.targetTreeEl)) { - _context8.next = 13; - break; - } - - _context8.next = 9; - return unfoldAndGetChildrenEl(info.closestPrev); - - case 9: - childrenEl = _context8.sent; - appendTo(store.placeholder, childrenEl); - _context8.next = 14; - break; - - case 13: - return _context8.abrupt("return", secondCase(info.closestPrev)); - - case 14: - case "end": - return _context8.stop(); - } - } - }, _callee8); - }))(); - } - }; // second case for actions, when target position not droppable - // return true if moved - - var secondCase = /*#__PURE__*/function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(branchEl) { - var targetEl; - return _regeneratorRuntime.wrap(function _callee9$(_context9) { - while (1) { - switch (_context9.prev = _context9.next) { - case 0: - if (!branchEl) { - _context9.next = 5; - break; - } - - targetEl = options._findClosestDroppablePosition(branchEl, store.targetTreeEl); - - if (!targetEl) { - _context9.next = 5; - break; - } - - insertAfter(store.placeholder, targetEl); - return _context9.abrupt("return", true); - - case 5: - case "end": - return _context9.stop(); - } - } - }, _callee9); - })); - - return function secondCase(_x) { - return _ref2.apply(this, arguments); - }; - }(); // when action is after, first case and second case invalid, try prepend - // 当操作是'after', 第一种第二种情况无效时, 尝试prepend - - - var thirdCase = /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(branchEl) { - return _regeneratorRuntime.wrap(function _callee10$(_context10) { - while (1) { - switch (_context10.prev = _context10.next) { - case 0: - if (!(!options.ifNodeFolded(branchEl, store) && options.isNodeDroppable(branchEl, store.targetTreeEl))) { - _context10.next = 3; - break; - } - - _context10.next = 3; - return tryUnfoldAndPrepend(branchEl); - - case 3: - case "end": - return _context10.stop(); - } - } - }, _callee10); - })); - - return function thirdCase(_x2) { - return _ref3.apply(this, arguments); - }; - }(); - - var unfoldAndGetChildrenEl = /*#__PURE__*/function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(branch) { - var childrenEl; - return _regeneratorRuntime.wrap(function _callee11$(_context11) { - while (1) { - switch (_context11.prev = _context11.next) { - case 0: - _context11.next = 2; - return options.unfoldTargetNodeByEl(branch, store); - - case 2: - childrenEl = branch.querySelector(".".concat(options.childrenClass)); - - if (!childrenEl) { - childrenEl = store.tempChildren; - appendTo(childrenEl, branch); - } - - return _context11.abrupt("return", childrenEl); - - case 5: - case "end": - return _context11.stop(); - } - } - }, _callee11); - })); - - return function unfoldAndGetChildrenEl(_x3) { - return _ref4.apply(this, arguments); - }; - }(); - - var tryUnfoldAndPrepend = /*#__PURE__*/function () { - var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(branchEl) { - var func, oneMoveStore; - return _regeneratorRuntime.wrap(function _callee13$(_context13) { - while (1) { - switch (_context13.prev = _context13.next) { - case 0: - func = /*#__PURE__*/function () { - var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12() { - var childrenEl; - return _regeneratorRuntime.wrap(function _callee12$(_context12) { - while (1) { - switch (_context12.prev = _context12.next) { - case 0: - _context12.next = 2; - return unfoldAndGetChildrenEl(branchEl); - - case 2: - childrenEl = _context12.sent; - prependTo(store.placeholder, childrenEl); - - case 4: - case "end": - return _context12.stop(); - } - } - }, _callee12); - })); - - return function func() { - return _ref6.apply(this, arguments); - }; - }(); - - if (!options.ifNodeFolded(branchEl, store)) { - _context13.next = 6; - break; - } - - // delay if node folded - oneMoveStore = store.oneMoveStore; - setTimeout(function () { - // check if expired - if (oneMoveStore === store.oneMoveStore) { - func(); - } - }, options.unfoldWhenDragoverDelay); - _context13.next = 8; - break; - - case 6: - _context13.next = 8; - return func(); - - case 8: - case "end": - return _context13.stop(); - } - } - }, _callee13); - })); - - return function tryUnfoldAndPrepend(_x4) { - return _ref5.apply(this, arguments); - }; - }(); // actions end ======================================== - - - doDraggableDecision({ - options: options, - event: store.moveEvent, - store: store, - opt: dhOptions, - info: info, - conditions: conditions, - actions: actions, - doAction: doAction - }); - }, - afterMove: function afterMove(store, dhOptions) { - options.afterMove && options.afterMove(store, dhOptions); - }, - beforeDrop: function () { - var _beforeDrop = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(store, dhOptions) { - var endEvent, movingEl, placeholder, tempChildren, movedCount, targetTreeEl, startTreeEl, maskTree, maskTree2, pathChanged, getTargetPath; - return _regeneratorRuntime.wrap(function _callee14$(_context14) { - while (1) { - switch (_context14.prev = _context14.next) { - case 0: - getTargetPath = function _getTargetPath() { - // example - // startPath placeholderPath - // [0] [1] - // [0] [1, 0] - // [3, 1] [3, 3] - // [3, 1] [3, 3, 5] - // above targetPaths should be [0], [0, 0] [3, 2] [3, 2, 5] - var startTree = store.startTree, - targetTree = store.targetTree, - startPath = store.startPath, - placeholderPath = store.placeholderPath; - var targetPath = placeholderPath.slice(0); - - if (options.cloneWhenDrag !== true) { - if (startTree === targetTree) { - if (startPath.length <= targetPath.length) { - var sw = startPath.slice(0, startPath.length - 1); // without end - - var tw = targetPath.slice(0, sw.length); // same length with sw - - if (sw.toString() === tw.toString()) { - var endIndex = sw.length; - - if (startPath[endIndex] < targetPath[endIndex]) { - targetPath[endIndex] -= 1; - } else if (startPath[endIndex] === targetPath[endIndex]) ; - } - } - } - } - - return targetPath; - }; - - endEvent = store.endEvent; - movingEl = store.movedElement; // branch - - placeholder = store.placeholder, tempChildren = store.tempChildren, movedCount = store.movedCount, targetTreeEl = store.targetTreeEl, startTreeEl = store.startTreeEl; // use mask tree to avoid flick caused by DOM update in short time - // 复制 targetTreeEl 作为遮罩, 避免短时间内更新DOM引起的闪烁 - - if (targetTreeEl) { - // No targetTreeEl mean no valid move. - // targetTreeEl不存在意味着没有有效移动. - // create mask tree - maskTree = targetTreeEl.cloneNode(true); - targetTreeEl.style.display = 'none'; - insertAfter(maskTree, targetTreeEl); - - if (startTreeEl !== targetTreeEl) { - maskTree2 = startTreeEl.cloneNode(true); - startTreeEl.style.display = 'none'; - insertAfter(maskTree2, startTreeEl); - } // - - - store.placeholderPath = options.getPathByBranchEl(placeholder); - store.targetPath = getTargetPath(); - pathChanged = targetTreeEl === startTreeEl && store.targetPath.toString() !== store.startPath.toString(); - store.pathChangePrevented = false; - - if (options.beforeDrop && options.beforeDrop(pathChanged, store, dhOptions) === false) { - pathChanged = false; - store.pathChangePrevented = false; - } - - store.pathChanged = pathChanged; - } // destroy placeholder and tempChildren - - - removeEl(placeholder); - - if (tempChildren) { - removeEl(tempChildren); - } - - store.updateMovedElementStyle(); // - - _context14.next = 10; - return options.afterDrop(store, dhOptions); - - case 10: - if (!maskTree) { - _context14.next = 16; - break; - } - - _context14.next = 13; - return waitTime(0); - - case 13: - removeEl(maskTree); - targetTreeEl.style.display = 'block'; - - if (maskTree2) { - removeEl(maskTree2); - startTreeEl.style.display = 'block'; - } - - case 16: - case "end": - return _context14.stop(); - } - } - }, _callee14); - })); - - function beforeDrop(_x5, _x6) { - return _beforeDrop.apply(this, arguments); - } - - return beforeDrop; - }() - }), - destroy = _draggableHelper.destroy, - draggableHelperOptions = _draggableHelper.options; - - return { - destroy: destroy, - options: options, - optionsUpdated: optionsUpdated - }; - - function getParentBranchByEl(el) { - return findParent(el, function (el) { - if (hasClass(el, options.branchClass)) { - return true; - } - - if (hasClass(el, options.rootClass)) { - return 'break'; - } - }); - } - - function optionsUpdated() { - Object.assign(draggableHelperOptions, { - triggerClassName: options.triggerClass, - triggerBySelf: options.triggerBySelf, - draggingClassName: options.draggingClass, - clone: options.cloneWhenDrag, - // edgeScroll - edgeScroll: options.edgeScroll, - edgeScrollTriggerMargin: options.edgeScrollTriggerMargin, - edgeScrollSpeed: options.edgeScrollSpeed, - edgeScrollTriggerMode: options.edgeScrollTriggerMode, - // - rtl: options.rtl, - preventTextSelection: options.preventTextSelection - }); - } -} - -function isElementHidden(el) { - return el.offsetWidth === 0 && el.offsetHeight === 0; -} - -function _createForOfIteratorHelper$2(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); } - -function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } -var treesStore = {}; -var script = { - props: { - triggerClass: { - type: [String, Array], - default: 'tree-node' - }, - triggerBySelf: { - type: Boolean - }, - draggable: { - type: [Boolean, Function], - default: true - }, - droppable: { - type: [Boolean, Function], - default: true - }, - eachDraggable: { - type: [Function] - }, - // type: [Boolean, Function] - eachDroppable: { - type: [Function] - }, - // type: [Boolean, Function] - ondragstart: { - type: Function - }, - ondragend: { - type: Function - }, - unfoldWhenDragover: { - type: Boolean, - default: true - }, - unfoldWhenDragoverDelay: { - type: Number, - default: 30 - }, - draggingNodePositionMode: { - type: String, - default: 'top_left_corner' - }, - // top_left_corner, mouse - edgeScroll: { - type: Boolean - }, - edgeScrollTriggerMargin: { - type: Number, - default: 50 - }, - edgeScrollSpeed: { - type: Number, - default: 0.35 - }, - edgeScrollTriggerMode: { - type: String, - default: 'top_left_corner' - }, - edgeScrollSpecifiedContainerX: {}, - // HTMLElement || ((store) => HTMLElement) - edgeScrollSpecifiedContainerY: {}, - // HTMLElement || ((store) => HTMLElement) - preventTextSelection: { - type: Boolean, - default: true - } - }, - // components: {}, - data: function data() { - return { - treesStore: treesStore - }; - }, - // computed: {}, - // watch: {}, - methods: { - _Draggable_unfoldTargetNodeByEl: function _Draggable_unfoldTargetNodeByEl(branchEl, store) { - var targetTree = store.targetTree; - var path = targetTree.getPathByBranchEl(branchEl); - var node = targetTree.getNodeByPath(path); - targetTree.unfold && targetTree.unfold(node, path); - return new Promise(function (resolve, reject) { - targetTree.$nextTick(function () { - resolve(); - }); - }); - }, - isNodeDraggable: function isNodeDraggable(node, path) { - var store = this.treesStore.store; - var allNodes = this.getAllNodesByPath(path); - allNodes.unshift(this.rootNode); - - var _iterator = _createForOfIteratorHelper$2(iterateAll(allNodes, { - reverse: true - })), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _step$value = _step.value, - _node = _step$value.value, - index = _step$value.index; - var currentPath = path.slice(0, index + 1); - var draggableOpt = _node.$draggable !== undefined ? _node.$draggable : this.eachDraggable; - var draggable = resolveValueOrGettter(draggableOpt, [currentPath, this, store]); - - if (draggable === undefined) { - continue; - } else { - return draggable; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return true; - }, - isNodeDroppable: function isNodeDroppable(node, path) { - var store = this.treesStore.store; - var allNodes = this.getAllNodesByPath(path); - allNodes.unshift(this.rootNode); - var droppableFinal, resolved; - - var _iterator2 = _createForOfIteratorHelper$2(iterateAll(allNodes, { - reverse: true - })), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var _step2$value = _step2.value, - _node2 = _step2$value.value, - index = _step2$value.index; - var currentPath = path.slice(0, index + 1); - var droppableOpt = _node2.$droppable !== undefined ? _node2.$droppable : this.eachDroppable; - var droppable = resolveValueOrGettter(droppableOpt, [currentPath, this, store]); - - if (droppable === undefined) { - continue; - } else { - droppableFinal = droppable; - resolved = true; - break; - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - - if (!resolved) { - droppableFinal = true; - } - - if (this._internal_hook_isNodeDroppable) { - return this._internal_hook_isNodeDroppable({ - droppableFinal: droppableFinal, - node: node, - path: path, - store: store - }); - } - - return droppableFinal; - }, - // override - getPathByBranchEl: function getPathByBranchEl(branchEl) { - var store = this.treesStore.store; - - var getAttrPath = function getAttrPath(el) { - var pathStr = el.getAttribute('data-tree-node-path'); - - if (pathStr) { - return pathStr.split(',').map(function (v) { - return parseInt(v); - }); - } - }; - - var path = getAttrPath(branchEl); - - if (path) { - return path; - } // placeholder path - - - var parentPath; - findParent(branchEl, function (el) { - if (hasClass(el, 'tree-root')) { - parentPath = []; - return true; - } - - if (hasClass(el, 'tree-branch')) { - parentPath = getAttrPath(el); - return true; - } - }); - var index = 0; - - var _iterator3 = _createForOfIteratorHelper$2(iterateAll(branchEl.parentElement.children)), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _step3$value = _step3.value, - el = _step3$value.value, - index2 = _step3$value.index; - - if (hasClass(el, 'tree-branch') || hasClass(el, 'tree-placeholder')) { - if (el === branchEl) { - break; - } - - index++; - } - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - return [].concat(_toConsumableArray(parentPath), [index]); - } - }, - // created() {}, - mounted: function mounted() { - var _this = this; - - var options = this._draggableOptions = { - indent: this.indent, - triggerClass: this.triggerClass, - triggerBySelf: this.triggerBySelf, - unfoldWhenDragover: this.unfoldWhenDragover, - unfoldWhenDragoverDelay: this.unfoldWhenDragoverDelay, - draggingNodePositionMode: this.draggingNodePositionMode, - cloneWhenDrag: this.cloneWhenDrag, - edgeScroll: this.edgeScroll, - edgeScrollTriggerMargin: this.edgeScrollTriggerMargin, - edgeScrollSpeed: this.edgeScrollSpeed, - edgeScrollTriggerMode: this.edgeScrollTriggerMode, - edgeScrollSpecifiedContainerX: this.edgeScrollSpecifiedContainerX, - edgeScrollSpecifiedContainerY: this.edgeScrollSpecifiedContainerY, - rtl: this.rtl, - preventTextSelection: this.preventTextSelection, - treeClass: 'he-tree', - rootClass: 'tree-root', - childrenClass: 'tree-children', - branchClass: 'tree-branch', - nodeClass: 'tree-node', - nodeBackClass: 'tree-node-back', - placeholderClass: 'tree-placeholder', - placeholderNodeBackClass: 'tree-placeholder-node-back', - placeholderNodeClass: 'tree-placeholder-node', - draggingClass: 'dragging', - placeholderId: "he_tree_drag_placeholder", - ifNodeFolded: function ifNodeFolded(branchEl, store) { - var targetTree = store.targetTree; - var node = targetTree.getNodeByBranchEl(branchEl); - return node.$folded; - }, - isTargetTreeRootDroppable: function isTargetTreeRootDroppable(store) { - var droppable = resolveValueOrGettter(store.targetTree.rootNode.$droppable, [store.targetTree, store]); - - if (droppable !== undefined) { - return droppable; - } - - return true; - }, - unfoldTargetNodeByEl: function unfoldTargetNodeByEl() { - return _this._Draggable_unfoldTargetNodeByEl.apply(_this, arguments); - }, - isNodeParentDroppable: function isNodeParentDroppable(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var parentPath = arrayWithoutEnd(path, 1); - var parent = tree.getNodeByPath(parentPath); - return tree.isNodeDroppable(parent, parentPath); - }, - isNodeDroppable: function isNodeDroppable(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var node = tree.getNodeByPath(path); - return tree.isNodeDroppable(node, path); - }, - _findClosestDroppablePosition: function _findClosestDroppablePosition(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var findPath = arrayWithoutEnd(path, 1); - var cur = path; - - var _iterator4 = _createForOfIteratorHelper$2(tree.iteratePath(findPath, { - reverse: true - })), - _step4; - - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var _step4$value = _step4.value, - node = _step4$value.node, - _path = _step4$value.path; - - if (tree.isNodeDroppable(node, _path)) { - return tree.getBranchElByPath(cur); - } else { - cur = _path; - } - } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); - } - - if (tree.isNodeDroppable(_this.rootNode, [])) { - return tree.getBranchElByPath(cur); - } - }, - afterPlaceholderCreated: function afterPlaceholderCreated(store) { - store.startTree.$emit('afterPlaceholderCreated', store); - store.startTree.$emit('after-placeholder-created', store); - }, - getPathByBranchEl: function getPathByBranchEl(branchEl) { - return _this.getPathByBranchEl(branchEl); - }, - beforeFirstMove: function beforeFirstMove(store) { - _this.treesStore.store = store; - store.startTree = _this.getTreeVmByTreeEl(store.startTreeEl); - var draggable = resolveValueOrGettter(store.startTree.draggable, [store.startTree, store]); - - if (!draggable) { - return false; - } - - var startTree = store.startTree, - dragBranchEl = store.dragBranchEl, - startPath = store.startPath; - store.dragNode = startTree.getNodeByPath(startPath); - - if (_this.cloneWhenDrag) { - store.dragNode = cloneTreeData(store.dragNode); - } - - if (!startTree.isNodeDraggable(store.dragNode, startPath)) { - return false; - } - - if (startTree.hasHook('ondragstart') && startTree.executeHook('ondragstart', [startTree, store]) === false) { - return false; - } - - store.startTree.$emit('before-first-move', store); - store.startTree.$emit('drag', store); - - _this.$root.$emit('he-tree-drag', store); - }, - filterTargetTree: function filterTargetTree(targetTreeEl, store) { - var targetTree = _this.getTreeVmByTreeEl(targetTreeEl); - - var startTree = store.startTree; - - if (startTree !== targetTree) { - if (_this._internal_hook_filterTargetTree) { - if (_this._internal_hook_filterTargetTree(targetTree, store) === false) { - return false; - } - } else { - return false; - } - } - - var targetTreeDroppable = resolveValueOrGettter(targetTree.droppable, [targetTree, store]); - - if (!targetTreeDroppable) { - return false; - } - - store.targetTree = targetTree; - - if (!resolveValueOrGettter(store.startTree === store.targetTree) && resolveValueOrGettter(_this._Draggable_unfoldTargetNode, [false, _this.treeData]) !== _this.rootNode.children) { - return false; - } - }, - afterMove: function afterMove(store) { - store.startTree.$emit('after-move', store); - }, - beforeDrop: function beforeDrop(pathChanged, store) { - var targetTree = store.targetTree; - - if (targetTree.hasHook('ondragend') && targetTree.executeHook('ondragend', [targetTree, store]) === false) { - return false; - } - - _this.$root.$emit('he-tree-before-drop', store); - }, - afterDrop: function afterDrop(store, t) { - if (store.pathChanged) { - var startTree = store.startTree, - targetTree = store.targetTree, - startPath = store.startPath, - dragNode = store.dragNode; - var targetPath = store.targetPath; - - if (_this.cloneWhenDrag !== true) { - // remove from start position - var startParentPath = arrayWithoutEnd(startPath, 1); - var startParent = startTree.getNodeByPath(startParentPath); - var startSiblings = startParentPath.length === 0 ? startTree.treeData : startParent.children; - var startIndex = arrayLast(startPath); - startSiblings.splice(startIndex, 1); - } // insert to target position - - - var targetParentPath = arrayWithoutEnd(targetPath, 1); - var targetParent = targetTree.getNodeByPath(targetParentPath); - var targetSiblings; - - if (targetParentPath.length === 0) { - targetSiblings = targetTree.treeData; - } else { - if (!targetParent.children) { - _this.$set(targetParent, 'children', []); - } - - targetSiblings = targetParent.children; - } - - var targetIndex = arrayLast(targetPath); - targetSiblings.splice(targetIndex, 0, dragNode); // emit event - - startTree.$emit('input', startTree.treeData); - startTree.$emit('change', store); - targetTree.$emit('drop', store); - - _this.$root.$emit('he-tree-drop', store); - - if (targetTree !== startTree) { - targetTree.$emit('input', targetTree.treeData); - targetTree.$emit('change', store); - } - - return new Promise(function (resolve, reject) { - targetTree.$nextTick(function () { - resolve(); - }); - }); - } - } - }; - - var _makeTreeDraggable_obj = this._makeTreeDraggable_obj = makeTreeDraggable(this.$el, options); // watch props and update options - - - ['indent', 'triggerClass', 'triggerBySelf', 'unfoldWhenDragover', 'unfoldWhenDragoverDelay', 'draggingNodePositionMode', 'cloneWhenDrag', 'edgeScroll', 'edgeScrollTriggerMargin', 'edgeScrollSpeed', 'edgeScrollTriggerMode', 'edgeScrollSpecifiedContainerY', 'edgeScrollSpecifiedContainerY', 'rtl', 'preventTextSelection'].forEach(function (name) { - _this.$watch(name, function (value) { - _makeTreeDraggable_obj.options[name] = value; - - _makeTreeDraggable_obj.optionsUpdated(); - }); - }); - } -}; - -/* script */ -var __vue_script__$1 = script; -/* template */ - -/* style */ - -var __vue_inject_styles__$1 = undefined; -/* scoped */ - -var __vue_scope_id__$1 = undefined; -/* module identifier */ - -var __vue_module_identifier__$1 = undefined; -/* functional template */ - -var __vue_is_functional_template__$1 = undefined; -/* style inject */ - -/* style inject SSR */ - -/* style inject shadow dom */ - -var __vue_component__$1 = /*#__PURE__*/__vue_normalize__({}, __vue_inject_styles__$1, __vue_script__$1, __vue_scope_id__$1, __vue_is_functional_template__$1, __vue_module_identifier__$1, false, undefined, undefined, undefined); - -export { check as Check, __vue_component__$1 as Draggable, fold as Fold, __vue_component__ as Tree, cloneTreeData, foldAll, getPureTreeData, unfoldAll, walkTreeData }; diff --git a/dist/he-tree-vue.js b/dist/he-tree-vue.js deleted file mode 100644 index ce90d1f..0000000 --- a/dist/he-tree-vue.js +++ /dev/null @@ -1,5315 +0,0 @@ -/*! - * he-tree-vue v2.0.11.beta.3 - * (c) phphe (https://github.com/phphe) - * Homepage: https://he-tree-vue.phphe.com - * Released under the MIT License. - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue')) : - typeof define === 'function' && define.amd ? define(['exports', 'vue'], factory) : - (global = global || self, factory(global.heTreeVue = {}, global.Vue)); -}(this, (function (exports, Vue) { 'use strict'; - - Vue = Vue && Object.prototype.hasOwnProperty.call(Vue, 'default') ? Vue['default'] : Vue; - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } - - var arrayLikeToArray = _arrayLikeToArray; - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return arrayLikeToArray(arr); - } - - var arrayWithoutHoles = _arrayWithoutHoles; - - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - var iterableToArray = _iterableToArray; - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); - } - - var unsupportedIterableToArray = _unsupportedIterableToArray; - - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var nonIterableSpread = _nonIterableSpread; - - function _toConsumableArray(arr) { - return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); - } - - var toConsumableArray = _toConsumableArray; - - 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 defineProperty = _defineProperty; - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var getPrototypeOf = createCommonjsModule(function (module) { - 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; - }); - - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = getPrototypeOf(object); - if (object === null) break; - } - - return object; - } - - var superPropBase = _superPropBase; - - var get = createCommonjsModule(function (module) { - function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - module.exports = _get = Reflect.get; - } else { - module.exports = _get = function _get(target, property, receiver) { - var base = superPropBase(target, property); - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.get) { - return desc.get.call(receiver); - } - - return desc.value; - }; - } - - return _get(target, property, receiver || target); - } - - module.exports = _get; - }); - - var setPrototypeOf = createCommonjsModule(function (module) { - 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; - }); - - var _typeof_1 = createCommonjsModule(function (module) { - 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; - }); - - 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; - } - - var createClass = _createClass; - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - var classCallCheck = _classCallCheck; - - var runtime_1 = createCommonjsModule(function (module) { - /** - * Copyright (c) 2014-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 runtime = (function (exports) { - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined$1; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - exports.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - exports.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - exports.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - exports.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator, PromiseImpl) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return PromiseImpl.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return PromiseImpl.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function(error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new PromiseImpl(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - exports.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { - if (PromiseImpl === void 0) PromiseImpl = Promise; - - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList), - PromiseImpl - ); - - return exports.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined$1) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined$1; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined$1; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - exports.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined$1; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - exports.values = values; - - function doneResult() { - return { value: undefined$1, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined$1; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined$1; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined$1; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined$1; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined$1; - } - - return ContinueSentinel; - } - }; - - // Regardless of whether this script is executing as a CommonJS module - // or not, return the runtime object so that we can declare the variable - // regeneratorRuntime in the outer scope, which allows this module to be - // injected easily by `bin/regenerator --include-runtime script.js`. - return exports; - - }( - // If this script is executing as a CommonJS module, use module.exports - // as the regeneratorRuntime namespace. Otherwise create a new empty - // object. Either way, the resulting object will be used to initialize - // the regeneratorRuntime variable at the top of this file. - module.exports - )); - - try { - regeneratorRuntime = runtime; - } catch (accidentalStrictMode) { - // This module should not be running in strict mode, so the above - // assignment should always work unless something is misconfigured. Just - // in case runtime.js accidentally runs in strict mode, we can escape - // strict mode using a global Function call. This could conceivably fail - // if a Content Security Policy forbids using Function, but in that case - // the proper solution is to fix the accidental strict mode problem. If - // you've misconfigured your bundler to force strict mode and applied a - // CSP to forbid Function, and you're not willing to fix either of those - // problems, please detail your unique predicament in a GitHub issue. - Function("r", "regeneratorRuntime = r")(runtime); - } - }); - - var regenerator = runtime_1; - - /*! - * helper-js v2.0.1 - * (c) phphe (https://github.com/phphe) - * Homepage: undefined - * Released under the MIT License. - */ - - var _marked = /*#__PURE__*/regenerator.mark(iterateAll); - - function _createForOfIteratorHelper(o) { - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (o = _unsupportedIterableToArray$1(o))) { - var i = 0; - - var F = function F() {}; - - return { - s: F, - n: function n() { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function e(_e) { - throw _e; - }, - f: F - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var it, - normalCompletion = true, - didErr = false, - err; - return { - s: function s() { - it = o[Symbol.iterator](); - }, - n: function n() { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function e(_e2) { - didErr = true; - err = _e2; - }, - f: function f() { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; - } - - function _unsupportedIterableToArray$1(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(n); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); - } - - function _arrayLikeToArray$1(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } // 为此库有需要的方法存储信息 - - function isArray(v) { - return Object.prototype.toString.call(v) === '[object Array]'; - } - - function isObject(v) { - return Object.prototype.toString.call(v) === '[object Object]'; - } - - function isFunction(v) { - return typeof v === 'function'; - } - // 返回指定范围随机整数, 包括范围起始值和终止值 - - - function randInt(min, max) { - return Math.floor(Math.random() * (max - min + 1) + min); - } // rand item in array - // 返回数组随机一项 - - - function randChoice(arr) { - return arr[randInt(0, arr.length - 1)]; - } // Pad a string to a certain length with another string - // 随机字符串 - - - function randString() { - var len = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; - var seeds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - var r = ''; - - for (var i = 0; i < len; i++) { - r += randChoice(seeds); - } - - return r; - } // ## Array - // ## 数组 - // remove item from array. return removed count - // 从数组删除项. 返回删除计数 - - - function arrayRemove(arr, v) { - var index; - var count = 0; - - while ((index = arr.indexOf(v)) > -1) { - arr.splice(index, 1); - count++; - } - - return count; - } // remove items from array by sorted indexes. indexes example: [0, 2, 6, 8, 9] - // 返回数组末项 - - - function arrayLast(arr) { - return arr[arr.length - 1]; - } // return arr1 - arr2 - - function toArrayIfNot(arrOrNot) { - return isArray(arrOrNot) ? arrOrNot : [arrOrNot]; - } - // 返回新数组排除末尾n项 - - - function arrayWithoutEnd(arr, n) { - return arr.slice(0, arr.length - n); - } // get one-dimensional array from multidimensional array - - function iterateAll(val) { - var opt, - i, - info, - _i2, - _Object$keys, - key, - _info, - _i3, - _info2, - keys, - _i4, - _keys, - _key, - _info3, - _args = arguments; - - return regenerator.wrap(function iterateAll$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - opt = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; - - if (opt.reverse) { - _context.next = 30; - break; - } - - if (!(val.length != null)) { - _context.next = 14; - break; - } - - i = 0; - - case 4: - if (!(i < val.length)) { - _context.next = 12; - break; - } - - info = { - value: val[i], - index: i - }; - - if (!(!opt.exclude || !opt.exclude(info))) { - _context.next = 9; - break; - } - - _context.next = 9; - return info; - - case 9: - i++; - _context.next = 4; - break; - - case 12: - _context.next = 28; - break; - - case 14: - if (!isObject(val)) { - _context.next = 27; - break; - } - - _i2 = 0, _Object$keys = Object.keys(val); - - case 16: - if (!(_i2 < _Object$keys.length)) { - _context.next = 25; - break; - } - - key = _Object$keys[_i2]; - _info = { - value: val[key], - key: key - }; - - if (!(!opt.exclude || !opt.exclude(_info))) { - _context.next = 22; - break; - } - - _context.next = 22; - return _info; - - case 22: - _i2++; - _context.next = 16; - break; - - case 25: - _context.next = 28; - break; - - case 27: - throw 'Unsupported type'; - - case 28: - _context.next = 58; - break; - - case 30: - if (!(val.length != null)) { - _context.next = 42; - break; - } - - _i3 = val.length - 1; - - case 32: - if (!(_i3 >= 0)) { - _context.next = 40; - break; - } - - _info2 = { - value: val[_i3], - index: _i3 - }; - - if (!(!opt.exclude || !opt.exclude(_info2))) { - _context.next = 37; - break; - } - - _context.next = 37; - return _info2; - - case 37: - _i3--; - _context.next = 32; - break; - - case 40: - _context.next = 58; - break; - - case 42: - if (!isObject(val)) { - _context.next = 57; - break; - } - - keys = Object.keys(val); - keys.reverse(); - _i4 = 0, _keys = keys; - - case 46: - if (!(_i4 < _keys.length)) { - _context.next = 55; - break; - } - - _key = _keys[_i4]; - _info3 = { - value: val[_key], - key: _key - }; - - if (!(!opt.exclude || !opt.exclude(_info3))) { - _context.next = 52; - break; - } - - _context.next = 52; - return _info3; - - case 52: - _i4++; - _context.next = 46; - break; - - case 55: - _context.next = 58; - break; - - case 57: - throw 'Unsupported type'; - - case 58: - case "end": - return _context.stop(); - } - } - }, _marked); - } // example: objectGet(window, 'document.body.children.0') . source: http://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path-to-it-as-string - - function objectAssignIfKeyNull(obj1, obj2) { - Object.keys(obj2).forEach(function (key) { - if (obj1[key] == null) { - obj1[key] = obj2[key]; - } - }); - } - - function depthFirstSearch(obj, handler) { - var childrenKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'children'; - var opt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - var rootChildren = isArray(obj) ? obj : [obj]; // - - var StopException = function StopException() { - classCallCheck(this, StopException); - }; - - var func = function func(children, parent, parentPath) { - if (opt.reverse) { - children = children.slice(); - children.reverse(); - } - - var len = children.length; - - for (var i = 0; i < len; i++) { - var item = children[i]; - var index = opt.reverse ? len - i - 1 : i; - var path = parentPath ? [].concat(toConsumableArray(parentPath), [index]) : []; - var r = handler(item, index, parent, path); - - if (r === false) { - // stop - throw new StopException(); - } else if (r === 'skip children') { - continue; - } else if (r === 'skip siblings') { - break; - } - - if (item[childrenKey] != null) { - func(item[childrenKey], item, path); - } - } - }; - - try { - func(rootChildren, null, isArray(obj) ? [] : null); - } catch (e) { - if (e instanceof StopException) ;else { - throw e; - } - } - } // refer [depthFirstSearch](#depthFirstSearch) - - - var walkTreeData = depthFirstSearch; // tree data helpers - - var TreeData = /*#__PURE__*/function () { - // data = null; - function TreeData() { - var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - - classCallCheck(this, TreeData); - - this.childrenKey = 'children'; - this.data = data; - } - - createClass(TreeData, [{ - key: "iteratePath", - value: /*#__PURE__*/regenerator.mark(function iteratePath(path) { - var opt, - childrenKey, - rootChildren, - prevPath, - prevChildren, - _iterator4, - _step4, - index, - currentPath, - currentNode, - list, - _iterator5, - _step5, - _step5$value, - path0, - node, - _path, - _args2 = arguments; - - return regenerator.wrap(function iteratePath$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - opt = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {}; - childrenKey = this.childrenKey, rootChildren = this.rootChildren; - - if (opt.reverse) { - _context2.next = 29; - break; - } - - prevPath = []; - prevChildren = rootChildren; - _iterator4 = _createForOfIteratorHelper(path); - _context2.prev = 6; - - _iterator4.s(); - - case 8: - if ((_step4 = _iterator4.n()).done) { - _context2.next = 19; - break; - } - - index = _step4.value; - currentPath = [].concat(toConsumableArray(prevPath), [index]); - currentNode = prevChildren[index]; - _context2.next = 14; - return { - path: currentPath, - node: currentNode - }; - - case 14: - prevPath = currentPath; - prevChildren = currentNode[childrenKey]; - - case 17: - _context2.next = 8; - break; - - case 19: - _context2.next = 24; - break; - - case 21: - _context2.prev = 21; - _context2.t0 = _context2["catch"](6); - - _iterator4.e(_context2.t0); - - case 24: - _context2.prev = 24; - - _iterator4.f(); - - return _context2.finish(24); - - case 27: - _context2.next = 49; - break; - - case 29: - list = toConsumableArray(this.iteratePath(path, Object.assign(Object.assign({}, opt), { - reverse: false - }))); - list.reverse(); - _iterator5 = _createForOfIteratorHelper(list); - _context2.prev = 32; - - _iterator5.s(); - - case 34: - if ((_step5 = _iterator5.n()).done) { - _context2.next = 41; - break; - } - - _step5$value = _step5.value, path0 = _step5$value.path, node = _step5$value.node; - _path = path0; - _context2.next = 39; - return { - path: _path, - node: node - }; - - case 39: - _context2.next = 34; - break; - - case 41: - _context2.next = 46; - break; - - case 43: - _context2.prev = 43; - _context2.t1 = _context2["catch"](32); - - _iterator5.e(_context2.t1); - - case 46: - _context2.prev = 46; - - _iterator5.f(); - - return _context2.finish(46); - - case 49: - case "end": - return _context2.stop(); - } - } - }, iteratePath, this, [[6, 21, 24, 27], [32, 43, 46, 49]]); - }) - }, { - key: "getAllNodes", - value: function getAllNodes(path) { - var all = []; - - var _iterator6 = _createForOfIteratorHelper(this.iteratePath(path)), - _step6; - - try { - for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { - var node = _step6.value.node; - all.push(node); - } - } catch (err) { - _iterator6.e(err); - } finally { - _iterator6.f(); - } - - return all; - } - }, { - key: "getNode", - value: function getNode(path) { - return arrayLast(this.getAllNodes(path)); - } - }, { - key: "getNodeIndexAndParent", - value: function getNodeIndexAndParent(path) { - var parentPath = path.slice(); - var index = parentPath.pop(); - return { - parent: this.getNode(parentPath), - index: index, - parentPath: parentPath - }; - } - }, { - key: "getNodeParent", - value: function getNodeParent(path) { - return this.getNodeIndexAndParent(path).parent; - } - }, { - key: "setPathNode", - value: function setPathNode(path, node) { - if (path == null || path.length === 0) { - this.data = node; - } else { - var childrenKey = this.childrenKey, - rootChildren = this.rootChildren; - - var _this$getNodeIndexAnd = this.getNodeIndexAndParent(path), - parent = _this$getNodeIndexAnd.parent, - index = _this$getNodeIndexAnd.index; - - var parentChildren = path.length === 1 ? rootChildren : parent[childrenKey]; - parentChildren[index] = node; - } - } - }, { - key: "removeNode", - value: function removeNode(path) { - var childrenKey = this.childrenKey, - rootChildren = this.rootChildren; - - var _this$getNodeIndexAnd2 = this.getNodeIndexAndParent(path), - parent = _this$getNodeIndexAnd2.parent, - index = _this$getNodeIndexAnd2.index; - - var parentChildren = path.length === 1 ? rootChildren : parent[childrenKey]; - var node = parentChildren[index]; - parentChildren.splice(index, 1); - return node; - } - }, { - key: "walk", - value: function walk(handler, opt) { - var childrenKey = this.childrenKey, - data = this.data; // @ts-ignore - - return walkTreeData(data, handler, childrenKey, opt); - } - }, { - key: "clone", - value: function clone() { - var opt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // opt.afterNodeCreated(newNode, {oldNode: node, index, parent, path}) - - var childrenKey = this.childrenKey; - var td = new TreeData(); - this.walk(function (node, index, parent, path) { - var newNode = Object.assign({}, node); - - if (newNode[childrenKey]) { - newNode[childrenKey] = []; - } - - if (opt.afterNodeCreated) { - opt.afterNodeCreated(newNode, { - oldNode: node, - index: index, - parent: parent, - path: path - }); - } - - td.setPathNode(path, newNode); - }); - return td.data; - } - }, { - key: "rootChildren", - get: function get() { - var childrenKey = this.childrenKey; - var data = this.data; - return isArray(data) ? data : data[childrenKey]; - } - }]); - - return TreeData; - }(); // ## function - // ## 函数 - // if it is function, return result, else return it directly. - - - function resolveValueOrGettter(valueOrGetter) { - var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - - if (isFunction(valueOrGetter)) { - return valueOrGetter.apply(void 0, toConsumableArray(args)); - } else { - return valueOrGetter; - } - } - - - function joinFunctionsByNext(funcs) { - var next = function next() {}; - - var _iterator7 = _createForOfIteratorHelper(iterateAll(funcs, { - reverse: true - })), - _step7; - - try { - for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { - var func = _step7.value.value; - var currentNext = next; - next = wrapFuncWithNext(func, currentNext); - } - } catch (err) { - _iterator7.e(err); - } finally { - _iterator7.f(); - } - - return next; - - function wrapFuncWithNext(func, next) { - return function () { - for (var _len4 = arguments.length, args = new Array(_len4), _key5 = 0; _key5 < _len4; _key5++) { - args[_key5] = arguments[_key5]; - } - - return func.apply(void 0, [next].concat(args)); - }; - } - } // ## promise - // return NodeList if there are multiple top-level nodes - - - function createElementFromHTML(htmlString) { - var div = document.createElement('div'); - div.innerHTML = htmlString.trim(); - - if (div.childNodes.length > 1) { - return div.childNodes; - } else { - return div.childNodes[0]; - } - } - - function isDescendantOf(el, parent) { - while (true) { - if (el.parentElement == null) { - return false; - } else if (el.parentElement === parent) { - return true; - } else { - el = el.parentElement; - } - } - } - - function removeEl(el) { - if (el.parentNode !== null) { - return el.parentNode.removeChild(el); - } - } // refer: https://stackoverflow.com/questions/871399/cross-browser-method-for-detecting-the-scrolltop-of-the-browser-window - - - function getScroll() { - if (typeof pageYOffset != 'undefined') { - //most browsers except IE before #9 - return { - top: pageYOffset, - left: pageXOffset - }; - } else { - var B = document.body; //IE 'quirks' - - var D = document.documentElement; //IE with doctype - - D = D.clientHeight ? D : B; - return { - top: D.scrollTop, - left: D.scrollLeft - }; - } - } // refer: https://gist.github.com/aderaaij/89547e34617b95ac29d1 - - - function getOffset(el) { - var rect = getBoundingClientRect(el); - var scroll = getScroll(); - return { - x: rect.left + scroll.left, - y: rect.top + scroll.top - }; - } // there is some trap in el.offsetParent, so use this func to fix - - function getBoundingClientRect(el) { - // refer: http://www.51xuediannao.com/javascript/getBoundingClientRect.html - var xy = el.getBoundingClientRect(); - var top = xy.top - document.documentElement.clientTop, - //document.documentElement.clientTop 在IE67中始终为2,其他高级点的浏览器为0 - bottom = xy.bottom, - left = xy.left - document.documentElement.clientLeft, - //document.documentElement.clientLeft 在IE67中始终为2,其他高级点的浏览器为0 - right = xy.right, - width = xy.width || right - left, - //IE67不存在width 使用right - left获得 - height = xy.height || bottom - top; - var x = left; - var y = top; - return { - top: top, - right: right, - bottom: bottom, - left: left, - width: width, - height: height, - x: x, - y: y - }; - } // refer [getBoundingClientRect](#getBoundingClientRect) - - - var getViewportPosition = getBoundingClientRect; // TODO not tested - - function findParent(el, callback) { - var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var cur = opt && opt.withSelf ? el : el.parentElement; - - while (cur) { - var r = callback(cur); - - if (r === 'break') { - return; - } else if (r) { - return cur; - } else { - cur = cur.parentElement; - } - } - } - - function backupAttr(el, name) { - var key = "original_".concat(name); - el[key] = el.getAttribute(name); - } - - function restoreAttr(el, name) { - var key = "original_".concat(name); - var value = el[key]; - - if (value == null) { - el.removeAttribute(name); - } else { - el.setAttribute(name, value); - } - } // source: http://youmightnotneedjquery.com/ - - - function hasClass(el, className) { - if (el.classList) { - return el.classList.contains(className); - } else { - return new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className); - } - } // source: http://youmightnotneedjquery.com/ - - - function addClass(el, className) { - if (!hasClass(el, className)) { - if (el.classList) { - el.classList.add(className); - } else { - el.className += ' ' + className; - } - } - } // source: http://youmightnotneedjquery.com/ - - function onDOM(el, name, handler) { - for (var _len5 = arguments.length, args = new Array(_len5 > 3 ? _len5 - 3 : 0), _key6 = 3; _key6 < _len5; _key6++) { - args[_key6 - 3] = arguments[_key6]; - } - - if (el.addEventListener) { - // 所有主流浏览器,除了 IE 8 及更早 IE版本 - el.addEventListener.apply(el, [name, handler].concat(args)); // @ts-ignore - } else if (el.attachEvent) { - // IE 8 及更早 IE 版本 - // @ts-ignore - el.attachEvent.apply(el, ["on".concat(name), handler].concat(args)); - } - } - - function offDOM(el, name, handler) { - for (var _len6 = arguments.length, args = new Array(_len6 > 3 ? _len6 - 3 : 0), _key7 = 3; _key7 < _len6; _key7++) { - args[_key7 - 3] = arguments[_key7]; - } - - if (el.removeEventListener) { - // 所有主流浏览器,除了 IE 8 及更早 IE版本 - el.removeEventListener.apply(el, [name, handler].concat(args)); // @ts-ignore - } else if (el.detachEvent) { - // IE 8 及更早 IE 版本 - // @ts-ignore - el.detachEvent.apply(el, ["on".concat(name), handler].concat(args)); - } - } - - function findNodeList(list, callback) { - var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var iterator = iterateAll(list, { - reverse: opt.reverse - }); - - var _iterator13 = _createForOfIteratorHelper(iterator), - _step13; - - try { - for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) { - var _step13$value = _step13.value, - value = _step13$value.value, - index = _step13$value.index; - - if (callback(value, index)) { - return value; - } - } - } catch (err) { - _iterator13.e(err); - } finally { - _iterator13.f(); - } - } - - function elementsFromPoint(x, y) { - var args = [x, y]; // @ts-ignore - - var func = document.elementsFromPoint || document.msElementsFromPoint || elementsFromPoint; - return func.apply(document, args); - - function elementsFromPoint(x, y) { - var parents = []; - var parent = void 0; - - do { - if (parent !== document.elementFromPoint(x, y)) { - parent = document.elementFromPoint(x, y); - parents.push(parent); - parent.style.pointerEvents = 'none'; - } else { - parent = false; - } - } while (parent); - - parents.forEach(function (parent) { - return parent.style.pointerEvents = 'all'; - }); - return parents; - } - } - /* scroll to a positon with duration - from https://gist.github.com/andjosh/6764939 - interface options{ - x: number // nullable. don't scroll horizontally when null - y: number // nullable. don't scroll vertically when null - duration: number // default 0 - element: Element // default is the top scrollable element. - beforeEveryFrame: (count: number) => boolean|void // call before requestAnimationFrame execution. return false to stop - } - return stop - */ - - - function scrollTo(options) { - if (!options.element) { - options.element = document.scrollingElement || document.documentElement; - } - - if (options.duration == null) { - options.duration = 0; - } - - var x = options.x, - y = options.y, - duration = options.duration, - element = options.element; - var requestAnimationFrameId; - var count = 0; - - var startY = element.scrollTop, - changeY = y - startY, - startX = element.scrollLeft, - changeX = x - startX, - startDate = +new Date(), - animateScroll = function animateScroll() { - if (options.beforeEveryFrame && options.beforeEveryFrame(count) === false) { - return; - } - - var currentDate = new Date().getTime(); - var changedTime = currentDate - startDate; - - if (y != null) { - element.scrollTop = parseInt(calc(startY, changeY, changedTime, duration)); - } - - if (x != null) { - element.scrollLeft = parseInt(calc(startX, changeX, changedTime, duration)); - } - - if (changedTime < duration) { - requestAnimationFrameId = requestAnimationFrame(animateScroll); - } else { - if (y != null) { - element.scrollTop = y; - } - - if (x != null) { - element.scrollLeft = x; - } - } - - count++; - }; - - var stop = function stop() { - cancelAnimationFrame(requestAnimationFrameId); - }; - - animateScroll(); // return stop - - return stop; - - function calc(startValue, changeInValue, changedTime, duration) { - return startValue + changeInValue * (changedTime / duration); - } - } // ### DOM structure - - - function insertBefore(el, target) { - target.parentElement.insertBefore(el, target); - } - - function insertAfter(el, target) { - target.parentElement.insertBefore(el, target.nextSibling); - } - - function prependTo(el, target) { - target.insertBefore(el, target.firstChild); - } - - function appendTo(el, target) { - target.appendChild(el); - } // ## Date - - function binarySearch(arr, callback) { - var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - opt = Object.assign({ - start: 0, - end: arr.length - 1, - maxTimes: 1000 - }, opt); - var _opt = opt, - start = _opt.start, - end = _opt.end; - var _opt2 = opt, - returnNearestIfNoHit = _opt2.returnNearestIfNoHit, - maxTimes = _opt2.maxTimes; - var midNum; - var mid; - - if (start == null) { - start = 0; - end = arr.length - 1; - } - - var i = 0; - var r; - - while (start >= 0 && start <= end) { - if (i >= maxTimes) { - throw Error("binarySearch: loop times is over ".concat(maxTimes, ", you can increase the limit.")); - } - - midNum = Math.floor((end - start) / 2 + start); - mid = arr[midNum]; - r = callback(mid, i); - - if (r > 0) { - end = midNum - 1; - } else if (r < 0) { - start = midNum + 1; - } else { - return { - index: midNum, - value: mid, - count: i + 1, - hit: true - }; - } - - i++; - } - - return returnNearestIfNoHit ? { - index: midNum, - value: mid, - count: i + 1, - hit: false, - greater: r > 0 - } : null; - } // - - function waitTime(milliseconds, callback) { - return new Promise(function (resolve, reject) { - setTimeout(function () { - callback && callback(); - resolve(); - }, milliseconds); - }); - } - - var Cache = /*#__PURE__*/function () { - function Cache() { - classCallCheck(this, Cache); - - this.store = {}; - } - - createClass(Cache, [{ - key: "has", - value: function has(name) { - return this.store.hasOwnProperty(name); - } - }, { - key: "remember", - value: function remember(name, getter) { - if (!this.has(name)) { - this.store[name] = { - value: getter() - }; - } - - return this.store[name].value; - } - }, { - key: "forget", - value: function forget(name) { - if (name) { - if (this.has(name)) { - delete this.store[name]; - } - } else { - this.store = {}; - } - } - }]); - - return Cache; - }(); // attach cached getters to an object; can attach to self - - - function attachCache(obj, toCache) { - var cache = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Cache(); - - var _loop3 = function _loop3(key) { - var getter = toCache[key]; - Object.defineProperty(obj, key, { - get: function get() { - var _this9 = this; - - return cache.remember(key, function () { - return getter.call(_this9); - }); - } - }); - }; - - for (var key in toCache) { - _loop3(key); - } - } // for animation - - /*! - * vue-functions v2.0.6 - * (c) phphe (https://github.com/phphe) - * Homepage: undefined - * Released under the MIT License. - */ - /** - * [updatablePropsEvenUnbound description] - * @param {[type]} props [object or getter] - * @return {[type]} [description] - * props eg: { - value: {$localName: 'current', $localSetter: (value, vm)}, - } - default localName is `localProps_${name}` - */ - - - function updatablePropsEvenUnbound(props) { - if (isFunction(props)) { - props = props(); - } else { - // object - props = Object.assign({}, props); - } - - var standardProps = {}; // without key starts with `$` - - var _loop = function _loop(name) { - var prop = props[name]; // complete 补全选项 - - if (!prop.$localName) { - prop.$localName = "localProps_".concat(name); - } - - if (!prop.$localSetter) { - prop.$localSetter = function (value) { - return value; - }; - } // make standardProp - - - var standardProp = {}; - standardProps[name] = standardProp; - Object.keys(props[name]).forEach(function (key) { - if (key[0] !== '$') { - standardProp[key] = prop[key]; - } - }); - }; - - for (var name in props) { - _loop(name); - } - - var component = { - props: standardProps, - computed: {}, - watch: {} - }; - - component.data = function () { - var t = { - localValueOfUpdatableProps: {} - }; - - for (var _i = 0, _Object$keys = Object.keys(props); _i < _Object$keys.length; _i++) { - var _name = _Object$keys[_i]; - t.localValueOfUpdatableProps[_name] = this[_name]; - } - - return t; - }; - - var _loop2 = function _loop2() { - var name = _Object$keys2[_i2]; - var prop = props[name]; - - component.watch[name] = function (value) { - this.localValueOfUpdatableProps[name] = prop.$localSetter(value, this); - }; - - var localName = prop.$localName; - component.computed[localName] = { - get: function get() { - return this.localValueOfUpdatableProps[name]; - }, - set: function set(value) { - if (name === 'value') { - this.$emit('input', value); - } else { - this.$emit("update:".concat(name), value); - } - - this.localValueOfUpdatableProps[name] = prop.$localSetter(value, this); - } - }; - }; - - for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { - _loop2(); - } - - return component; - } - - var hookHelper = { - methods: { - // todo extract hooks to vue-functions - // get hooks in this._hooks, without which in props - _getNonPropHooksByName: function _getNonPropHooksByName(name) { - if (this._hooks) { - return this._hooks[name]; - } - }, - addHook: function addHook(name, func) { - if (!this._getNonPropHooksByName(name)) { - if (!this._hooks) { - this._hooks = {}; - } - - if (!this._hooks[name]) { - this._hooks[name] = []; - } - } - - this._hooks[name].push(func); - }, - removeHook: function removeHook(name, func) { - var hooks = this._getNonPropHooksByName(name); - - if (hooks) { - arrayRemove(hooks, func); - } - }, - hasHook: function hasHook(name) { - return this._getNonPropHooksByName(name) || this[name]; - }, - executeHook: function executeHook(name, args) { - var _this2 = this; - - var hooks = this._getNonPropHooksByName(name); - - hooks = hooks ? hooks.slice() : []; - - if (this[name] && isFunction(this[name])) { - hooks.push(function (next) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return _this2[name].apply(_this2, args); - }); - } - - return joinFunctionsByNext(hooks).apply(void 0, toConsumableArray(args)); - } - } - }; - - function cloneTreeData(treeData, opt) { - return new TreeData(treeData).clone(opt); - } - function walkTreeData$1(treeData, handler, opt) { - return new TreeData(treeData).walk(handler, opt); - } - function getPureTreeData(treeData) { - var opt = { - afterNodeCreated: function afterNodeCreated(newNode) { - Object.keys(newNode).forEach(function (key) { - if (key[0] === '$') { - delete newNode[key]; - } - }); - } - }; - return cloneTreeData(treeData, opt); - } - - 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) { 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; } - - var template = function template(h) { - var _this = this; - - // convert undefined to empty str - var noUndefined = function noUndefined(str) { - return str ? str : ''; - }; // tree tpl, to render recursively - - - var childrenListTpl = function childrenListTpl(nodes, parent, parentPath) { - var indentStyle = defineProperty({}, !_this.rtl ? 'paddingLeft' : 'paddingRight', parentPath.length * _this.indent + 'px'); - - var branchTpl = function branchTpl(node, index) { - var path = [].concat(toConsumableArray(parentPath), [index]); - var transitionComponent = _this.foldingTransition || 'transition'; - - var slotDefault = function slotDefault() { - var original = function original() { - if (_this.$scopedSlots.default) { - return _this.$scopedSlots.default({ - node: node, - index: index, - path: path, - tree: _this - }); - } else if (_this.$slots.default) { - return _this.$slots.default; - } else { - return node.text; - } - }; - - if (_this.overrideSlotDefault) { - return _this.overrideSlotDefault({ - node: node, - index: index, - path: path, - tree: _this - }, original); - } else { - return original(); - } - }; - - var nodebackStyle = indentStyle; - - if (node.$nodeBackStyle) { - nodebackStyle = _objectSpread(_objectSpread({}, nodebackStyle), node.$nodeBackStyle); - } - - return h("div", { - "class": "tree-branch ".concat(noUndefined(node.$branchClass), " ").concat(noUndefined(node.$hidden && 'he-tree--hidden')), - "style": node.$branchStyle || {}, - "attrs": { - "data-tree-node-path": path.join(',') - } - }, [h("div", { - "class": "tree-node-back ".concat(noUndefined(node.$nodeBackClass)), - "style": nodebackStyle || {} - }, [h("div", { - "class": "tree-node ".concat(noUndefined(node.$nodeClass)), - "style": node.$nodeStyle || {} - }, [slotDefault()])]), (node.children && node.children.length) > 0 && h(transitionComponent, { - "attrs": { - "name": _this.$props.foldingTransitionName - } - }, [!node.$folded && childrenListTpl(node.children, node, path)])]); - }; - - return h("div", { - "class": "tree-children ".concat(noUndefined(parent === _this.rootNode && 'tree-root'), " ").concat(noUndefined(parent.$childrenClass)), - "style": parent.$childrenStyle || {} - }, [nodes.map(branchTpl)]); - }; - - return h("div", { - "class": "he-tree ".concat(this.treeClass, " ").concat(noUndefined(this.rtl && 'he-tree--rtl')), - "attrs": { - "data-tree-id": this.treeId - } - }, [this.blockHeader && this.blockHeader(), childrenListTpl(this.rootNode.children, this.rootNode, []), this.blockFooter && this.blockFooter()]); - }; - - var trees = {}; - var Tree = { - render: template, - mixins: [updatablePropsEvenUnbound({ - value: { - $localName: 'treeData', - required: true - } - }), hookHelper], - props: { - indent: { - type: Number, - default: 20 - }, - rtl: { - type: Boolean - }, - rootNode: { - default: function _default(is) { - return {}; - } - } - }, - // components: {}, - data: function data() { - return { - trees: trees, - treeClass: '', - treeId: randString() - }; - }, - // computed: {}, - watch: { - treeData: { - immediate: true, - handler: function handler(treeData) { - this._TreeDataHelper = new TreeData(this.treeData); - } - } - }, - methods: { - iteratePath: function iteratePath(path, opt) { - return this._TreeDataHelper.iteratePath(path, opt); - }, - getTreeVmByTreeEl: function getTreeVmByTreeEl(treeEl) { - return this.trees[treeEl.getAttribute('data-tree-id')]; - }, - getAllNodesByPath: function getAllNodesByPath(path) { - return this._TreeDataHelper.getAllNodes(path); - }, - getNodeByPath: function getNodeByPath(path) { - return this._TreeDataHelper.getNode(path); - }, - getPathByBranchEl: function getPathByBranchEl(branchEl) { - return branchEl.getAttribute('data-tree-node-path').split(',').map(function (v) { - return parseInt(v); - }); - }, - getBranchElByPath: function getBranchElByPath(path) { - return this.$el.querySelector("[data-tree-node-path='".concat(path.join(','), "']")); - }, - getNodeByBranchEl: function getNodeByBranchEl(branchEl) { - return this.getNodeByPath(this.getPathByBranchEl(branchEl)); - }, - getNodeParentByPath: function getNodeParentByPath(path) { - return this._TreeDataHelper.getNodeParent(path); - }, - removeNodeByPath: function removeNodeByPath(path) { - return this._TreeDataHelper.removeNode(path); - }, - walkTreeData: function walkTreeData(handler, opt) { - return walkTreeData$1(this.treeData, handler, opt); - }, - cloneTreeData: function cloneTreeData$1(opt) { - return cloneTreeData(this.treeData, opt); - }, - // return cloned new tree data without property witch starts with `$` - getPureTreeData: function getPureTreeData$1() { - return getPureTreeData(this.treeData); - } - }, - created: function created() { - var _this2 = this; - - // - var updateRootNode = function updateRootNode() { - _this2.$set(_this2.rootNode, 'children', _this2.treeData); - }; - - this.$watch('rootNode', updateRootNode, { - immediate: true - }); - this.$watch('treeData', updateRootNode, { - immediate: true - }); - }, - mounted: function mounted() { - var _this3 = this; - - // - this.treeId = randString(); - this.$set(this.trees, this.treeId, this); - this.$once('hook:beforeDestroy', function () { - _this3.$delete(_this3.trees, _this3.treeId); - }); - }, - // beforeDestroy() {}, - // - mixPlugins: function mixPlugins(plugins) { - var MixedTree = { - name: 'Tree', - extends: Tree, - mixins: plugins, - mixPlugins: this.mixPlugins - }; - return MixedTree; - } - }; - - function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier - /* server only */ - , shadowMode, createInjector, createInjectorSSR, createInjectorShadow) { - if (typeof shadowMode !== 'boolean') { - createInjectorSSR = createInjector; - createInjector = shadowMode; - shadowMode = false; - } // Vue.extend constructor export interop. - - - var options = typeof script === 'function' ? script.options : script; // render functions - - if (template && template.render) { - options.render = template.render; - options.staticRenderFns = template.staticRenderFns; - options._compiled = true; // functional template - - if (isFunctionalTemplate) { - options.functional = true; - } - } // scopedId - - - if (scopeId) { - options._scopeId = scopeId; - } - - var hook; - - if (moduleIdentifier) { - // server build - hook = function hook(context) { - // 2.3 injection - context = context || // cached call - this.$vnode && this.$vnode.ssrContext || // stateful - this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional - // 2.2 with runInNewContext: true - - if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { - context = __VUE_SSR_CONTEXT__; - } // inject component styles - - - if (style) { - style.call(this, createInjectorSSR(context)); - } // register component module identifier for async chunk inference - - - if (context && context._registeredComponents) { - context._registeredComponents.add(moduleIdentifier); - } - }; // used by ssr in case component is cached and beforeCreate - // never gets called - - - options._ssrRegister = hook; - } else if (style) { - hook = shadowMode ? function (context) { - style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot)); - } : function (context) { - style.call(this, createInjector(context)); - }; - } - - if (hook) { - if (options.functional) { - // register for functional component in vue file - var originalRender = options.render; - - options.render = function renderWithStyleInjection(h, context) { - hook.call(context); - return originalRender(h, context); - }; - } else { - // inject component registration as beforeCreate hook - var existing = options.beforeCreate; - options.beforeCreate = existing ? [].concat(existing, hook) : [hook]; - } - } - - return script; - } - - /* script */ - var __vue_script__ = Tree; - /* template */ - - /* style */ - - var __vue_inject_styles__ = undefined; - /* scoped */ - - var __vue_scope_id__ = undefined; - /* module identifier */ - - var __vue_module_identifier__ = undefined; - /* functional template */ - - var __vue_is_functional_template__ = undefined; - /* style inject */ - - /* style inject SSR */ - - /* style inject shadow dom */ - - var __vue_component__ = /*#__PURE__*/normalizeComponent({}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, false, undefined, undefined, undefined); - - function ownKeys$1(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$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - function foldAll(treeData) { - walkTreeData$1(treeData, function (childNode) { - Vue.set(childNode, '$folded', true); - }); - } - function unfoldAll(treeData) { - walkTreeData$1(treeData, function (childNode) { - Vue.set(childNode, '$folded', false); - }); - } - var fold = { - props: { - foldingTransitionName: { - type: String - }, - foldingTransition: {}, - foldAllAfterMounted: { - type: Boolean - } - }, - methods: { - fold: function fold(node, path) { - if (!node.$folded) { - this.$set(node, '$folded', true); - this.$emit('nodeFoldedChanged', node); - } - }, - unfold: function unfold(node, path) { - var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - opt = _objectSpread$1({ - foldOthers: false - }, opt); - - if (opt.foldOthers) { - this.foldAll(); - } - - if (node.$folded) { - this.$set(node, '$folded', false); - this.$emit('nodeFoldedChanged', node); - this.$emit('node-folded-changed', node); - } - }, - toggleFold: function toggleFold(node, path, opt) { - if (node.$folded) { - this.unfold(node, path, opt); - } else { - this.fold(node, path, opt); - } - }, - foldAll: function foldAll() { - var _this = this; - - this.walkTreeData(function (childNode) { - _this.fold(childNode); - }); - }, - unfoldAll: function unfoldAll() { - var _this2 = this; - - this.walkTreeData(function (childNode) { - _this2.unfold(childNode, { - unfoldParent: false - }); - }); - } - }, - mounted: function mounted() { - if (this.foldAllAfterMounted) { - this.foldAll(); - } - } - }; - - function _createForOfIteratorHelper$1(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - - function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); } - - function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - var check = { - props: {}, - methods: { - afterCheckChanged: function afterCheckChanged(node, path) { - var _this = this; - - // update parent - var nodes = this.getAllNodesByPath(path); - var reversedParents = nodes.slice(0, nodes.length - 1); - reversedParents.reverse(); - - var _iterator = _createForOfIteratorHelper$1(reversedParents), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var parent = _step.value; - this.$set(parent, '$checked', parent.children.every(function (child) { - return child.$checked; - })); - } // update children - - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (node.children && node.children.length > 0) { - walkTreeData$1(node.children, function (childNode) { - _this.$set(childNode, '$checked', node.$checked); - }); - } - }, - check: function check(node, path) { - this.$set(node, '$checked', true); - this.afterCheckChanged(node, path); - }, - uncheck: function uncheck(node, path) { - this.$set(node, '$checked', false); - this.afterCheckChanged(node, path); - }, - toggleCheck: function toggleCheck(node, path) { - this.$set(node, '$checked', !node.$checked); - this.afterCheckChanged(node, path); - } - } - }; - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; - } - - var asyncToGenerator = _asyncToGenerator; - - /*! - * drag-event-service v1.1.7 - * (c) phphe (https://github.com/phphe) - * Homepage: undefined - * Released under the MIT License. - */ - var events = { - start: ['mousedown', 'touchstart'], - move: ['mousemove', 'touchmove'], - end: ['mouseup', 'touchend'] - }; - var DragEventService = { - isTouch: function isTouch(e) { - return e.type && e.type.startsWith('touch'); - }, - _getStore: function _getStore(el) { - if (!el._wrapperStore) { - el._wrapperStore = []; - } - - return el._wrapperStore; - }, - on: function on(el, name, handler, options) { - var _hp$onDOM, _hp$onDOM2; - - var _resolveOptions = resolveOptions(options), - args = _resolveOptions.args, - mouseArgs = _resolveOptions.mouseArgs, - touchArgs = _resolveOptions.touchArgs; - - var store = this._getStore(el); - - var ts = this; - - var wrapper = function wrapper(e) { - var mouse; - var isTouch = ts.isTouch(e); - - if (isTouch) { - // touch - mouse = { - x: e.changedTouches[0].pageX, - y: e.changedTouches[0].pageY, - pageX: e.changedTouches[0].pageX, - pageY: e.changedTouches[0].pageY, - clientX: e.changedTouches[0].clientX, - clientY: e.changedTouches[0].clientY, - screenX: e.changedTouches[0].screenX, - screenY: e.changedTouches[0].screenY - }; - } else { - // mouse - mouse = { - x: e.pageX, - y: e.pageY, - pageX: e.pageX, - pageY: e.pageY, - clientX: e.clientX, - clientY: e.clientY, - screenX: e.screenX, - screenY: e.screenY - }; - - if (name === 'start' && e.which !== 1) { - // not left button mousedown - return; - } - } - - return handler.call(this, e, mouse); - }; - - store.push({ - handler: handler, - wrapper: wrapper - }); // follow format will cause big bundle size - // 以下写法将会使打包工具认为hp是上下文, 导致打包整个hp - // hp.onDOM(el, events[name][0], wrapper, ...args) - - (_hp$onDOM = onDOM).call.apply(_hp$onDOM, [null, el, events[name][0], wrapper].concat([].concat(toConsumableArray(args), toConsumableArray(mouseArgs)))); - - (_hp$onDOM2 = onDOM).call.apply(_hp$onDOM2, [null, el, events[name][1], wrapper].concat([].concat(toConsumableArray(args), toConsumableArray(touchArgs)))); - }, - off: function off(el, name, handler, options) { - var _resolveOptions2 = resolveOptions(options), - args = _resolveOptions2.args, - mouseArgs = _resolveOptions2.mouseArgs; - - var store = this._getStore(el); - - for (var i = store.length - 1; i >= 0; i--) { - var _store$i = store[i], - handler2 = _store$i.handler, - wrapper = _store$i.wrapper; - - if (handler === handler2) { - var _hp$offDOM, _hp$offDOM2; - - (_hp$offDOM = offDOM).call.apply(_hp$offDOM, [null, el, events[name][0], wrapper].concat([].concat(toConsumableArray(args), toConsumableArray(mouseArgs)))); - - (_hp$offDOM2 = offDOM).call.apply(_hp$offDOM2, [null, el, events[name][1], wrapper].concat([].concat(toConsumableArray(args), toConsumableArray(mouseArgs)))); - - store.splice(i, 1); - } - } - } - }; - - function resolveOptions(options) { - if (!options) { - options = {}; - } - - var args = options.args || []; - var mouseArgs = options.mouseArgs || []; - var touchArgs = options.touchArgs || []; - return { - args: args, - mouseArgs: mouseArgs, - touchArgs: touchArgs - }; - } - - /*! - * draggable-helper v5.0.6 - * (c) phphe (https://github.com/phphe) - * Homepage: undefined - * Released under the MIT License. - */ - - function _createForOfIteratorHelper$2(o) { - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (o = _unsupportedIterableToArray$3(o))) { - var i = 0; - - var F = function F() {}; - - return { - s: F, - n: function n() { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function e(_e) { - throw _e; - }, - f: F - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var it, - normalCompletion = true, - didErr = false, - err; - return { - s: function s() { - it = o[Symbol.iterator](); - }, - n: function n() { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function e(_e2) { - didErr = true; - err = _e2; - }, - f: function f() { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; - } - - function _unsupportedIterableToArray$3(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray$3(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(n); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen); - } - - function _arrayLikeToArray$3(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } - /* Default export, a function. - ```js - import draggableHelper from 'draggable-helper' - draggableHelper(listenerElement, options) - ``` - Arguments: - listenerElement: HTMLElement. The element to bind mouse and touch event listener. - options: Options. Optional. - */ - - /* 默认导出, 一个方法. - ```js - import draggableHelper from 'draggable-helper' - draggableHelper(listenerElement, options) - ``` - 参数: - listenerElement: HTMLElement. 绑定鼠标和触摸事件监听器的HTML元素. - options: Options. 可选. - */ - - - var _edgeScroll = { - afterFirstMove: function afterFirstMove(store, opt) {}, - afterMove: function afterMove(store, opt) {}, - afterDrop: function afterDrop(store, opt) {} - }; - - function index(listenerElement) { - var opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var store; // set default value of options - // 设置options的默认值 - - objectAssignIfKeyNull(opt, defaultOptions); // define the event listener of mousedown and touchstart - // 定义mousedown和touchstart事件监听器 - - var onMousedownOrTouchStart = function onMousedownOrTouchStart(e, mouse) { - // execute native event hooks - if (!DragEventService.isTouch(e)) { - opt.onmousedown && opt.onmousedown(e); - } else { - opt.ontouchstart && opt.ontouchstart(e); - } - - var target = e.target; // check if triggered by ignore tags - // 检查是否由忽略的标签名触发 - - if (opt.ingoreTags.includes(target.tagName)) { - return; - } // check if trigger element and its parent has undraggable class name - // 检查触发事件的元素和其与element之间的父级是否有不允许拖动的类名 - - - if (hasClass(target, opt.undraggableClassName)) { - return; - } - - var isParentUndraggable = findParent(target, function (el) { - if (hasClass(el, opt.undraggableClassName)) { - return true; - } - - if (el === listenerElement) { - return 'break'; - } - }); - - if (isParentUndraggable) { - return; - } // Initialize store. Store start event, initial position - // 初始化store. 存储开始事件, 事件触发坐标 - - - store = JSON.parse(JSON.stringify(initialStore)); - store.startEvent = e; - store.listenerElement = listenerElement; - store.directTriggerElement = target; - store.initialMouse = Object.assign({}, mouse); // get triggerElement - - var triggerElementIsMovedOrClonedElement = false; - - if (opt.getTriggerElement) { - var el = opt.getTriggerElement(store.directTriggerElement, store); - - if (!el) { - return; - } - - store.triggerElement = el; - } else if (opt.triggerClassName) { - var triggerElement; - - var _iterator = _createForOfIteratorHelper$2(toArrayIfNot(opt.triggerClassName)), - _step; - - try { - var _loop = function _loop() { - var className = _step.value; - triggerElement = findParent(store.directTriggerElement, function (el) { - if (hasClass(el, className)) { - return true; - } - - if (el === listenerElement) { - return 'break'; - } - }, { - withSelf: true - }); - - if (triggerElement) { - return "break"; - } - }; - - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _ret = _loop(); - - if (_ret === "break") break; - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (!triggerElement) { - return; - } - - store.triggerElement = triggerElement; - } else { - triggerElementIsMovedOrClonedElement = true; - } // get movedOrClonedElement - - - store.movedOrClonedElement = opt.getMovedOrClonedElement ? opt.getMovedOrClonedElement(store.directTriggerElement, store, opt) : listenerElement; - - if (!store.movedOrClonedElement) { - return; - } - - if (triggerElementIsMovedOrClonedElement) { - store.triggerElement = store.movedOrClonedElement; - } // check if trigger element is same with directTriggerElement when options.triggerBySelf is true - // options.triggerBySelf为true时, 检查触发事件的元素是否是允许触发的元素 - - - if (opt.triggerBySelf && store.triggerElement !== store.directTriggerElement) { - return; - } // prevent text be selected - // 阻止文字被选中 - - - if (!DragEventService.isTouch(e)) { - // Do not prevent when touch. Or the elements within the node can not trigger click event. - // 不要在触摸时阻止事件. 否则将导致节点内的元素不触发点击事件. - if (opt.preventTextSelection) { - e.preventDefault(); - } - } // listen mousemove and touchmove - // 监听mousemove和touchmove - - - DragEventService.on(document, 'move', onMousemoveOrTouchMove, { - touchArgs: [{ - passive: false - }] - }); // listen mouseup and touchend - // 监听mouseup和touchend - - DragEventService.on(window, 'end', onMouseupOrTouchEnd); - }; // bind mousedown or touchstart event listener - // 绑定mousedown和touchstart事件监听器 - - - DragEventService.on(listenerElement, 'start', onMousedownOrTouchStart, { - touchArgs: [{ - passive: true - }] - }); // define the event listener of mousemove and touchmove - // 定义mousemove和touchmove事件监听器 - - var onMousemoveOrTouchMove = function onMousemoveOrTouchMove(e, mouse) { - // execute native event hooks - if (!DragEventService.isTouch(e)) { - opt.onmousemove && opt.onmousemove(e); - } else { - opt.ontouchmove && opt.ontouchmove(e); - } // - - - var _store = store, - movedOrClonedElement = _store.movedOrClonedElement; // calc move and attach related info to store - // 计算move并附加相关信息到store - - var move = store.move = { - x: mouse.clientX - store.initialMouse.clientX, - y: mouse.clientY - store.initialMouse.clientY - }; - store.moveEvent = e; - store.mouse = mouse; - - if (DragEventService.isTouch(e)) { - // prevent page scroll when touch. - // 当触摸时阻止屏幕被拖动. - e.preventDefault(); - } else { - // prevent text be selected - // 阻止文字被选中 - if (opt.preventTextSelection) { - e.preventDefault(); - } - } // first move - // 第一次移动 - - - if (store.movedCount === 0) { - // check if min displacement exceeded. - // 检查是否达到最小位移 - if (opt.minDisplacement) { - var x2 = Math.pow(move.x, 2); - var y2 = Math.pow(move.y, 2); - var dtc = Math.pow(x2 + y2, 0.5); - - if (dtc < opt.minDisplacement) { - return; - } - } // resolve elements - - - var movedElement = opt.clone ? movedOrClonedElement.cloneNode(true) : movedOrClonedElement; - var initialPosition = getViewportPosition(movedOrClonedElement); // attach elements and initialPosition to store - // 附加元素和初始位置到store - - store.movedOrClonedElement = movedOrClonedElement; - store.movedElement = movedElement; - store.initialPositionRelativeToViewport = initialPosition; - store.initialPosition = initialPosition; // define the function to update moved element style - // 定义更新移动元素样式的方法 - - var updateMovedElementStyle = function updateMovedElementStyle() { - if (opt.clone) { - store.movedOrClonedElement.parentElement.appendChild(movedElement); - } - - var size = getBoundingClientRect(movedElement); - var style = { - width: "".concat(Math.ceil(size.width), "px"), - height: "".concat(Math.ceil(size.height), "px"), - zIndex: 9999, - opacity: 0.8, - position: 'fixed', - left: initialPosition.x + 'px', - top: initialPosition.y + 'px', - pointerEvents: 'none' - }; - backupAttr(movedElement, 'style'); - - for (var key in style) { - movedElement.style[key] = style[key]; - } - - backupAttr(movedElement, 'class'); - addClass(movedElement, opt.draggingClassName); - /* - check if the changed position is expected and correct it. about stacking context. - 当某父元素使用了transform属性时, fixed不再以窗口左上角为坐标. 以下功能是在第一次移动后, 检查元素实际位置和期望位置是否相同, 不同则说明坐标系不是期望的. 则把初始位置减去偏移, 无论任何父元素导致了层叠上下文问题, 都能正确显示. - */ - - var nowPosition = getViewportPosition(movedElement); - - if (nowPosition.x !== initialPosition.x) { - initialPosition.x = initialPosition.x - (nowPosition.x - initialPosition.x); - initialPosition.y = initialPosition.y - (nowPosition.y - initialPosition.y); - movedElement.style.left = initialPosition.x + 'px'; - movedElement.style.top = initialPosition.y + 'px'; - } - }; - - store.updateMovedElementStyle = updateMovedElementStyle; // call hook beforeFirstMove, beforeMove - - if (opt.beforeFirstMove && opt.beforeFirstMove(store, opt) === false) { - return; - } - - if (opt.beforeMove && opt.beforeMove(store, opt) === false) { - return; - } // try to update moved element style - // 尝试更新移动元素样式 - - - if (!opt.updateMovedElementStyleManually) { - store.updateMovedElementStyle(); - } - - _edgeScroll.afterFirstMove(store, opt); - - opt.afterFirstMove && opt.afterFirstMove(store, opt); - } // Not the first move - // 非第一次移动 - else { - // define the function to update moved element style - // 定义更新移动元素样式的方法 - var _updateMovedElementStyle = function _updateMovedElementStyle() { - Object.assign(store.movedElement.style, { - left: store.initialPosition.x + move.x + 'px', - top: store.initialPosition.y + move.y + 'px' - }); - }; - - store.updateMovedElementStyle = _updateMovedElementStyle; // call hook beforeMove - - if (opt.beforeMove && opt.beforeMove(store, opt) === false) { - return; - } // try to update moved element style - // 尝试更新移动元素样式 - - - if (!opt.updateMovedElementStyleManually) { - store.updateMovedElementStyle(); - } - } - - _edgeScroll.afterMove(store, opt); - - store.movedCount++; - opt.afterMove && opt.afterMove(store, opt); - }; // define the event listener of mouseup and touchend - // 定义mouseup和touchend事件监听器 - - - var onMouseupOrTouchEnd = function onMouseupOrTouchEnd(e) { - // execute native event hooks - if (!DragEventService.isTouch(e)) { - opt.onmousedown && opt.onmousedown(e); - } else { - opt.ontouchend && opt.ontouchend(e); - } // cancel listening mousemove, touchmove, mouseup, touchend - // 取消监听事件mousemove, touchmove, mouseup, touchend - - - DragEventService.off(document, 'move', onMousemoveOrTouchMove, { - touchArgs: [{ - passive: false - }] - }); - DragEventService.off(window, 'end', onMouseupOrTouchEnd); // - - if (store.movedCount === 0) { - return; - } - - store.endEvent = e; - var _store2 = store, - movedElement = _store2.movedElement; // define the function to update moved element style - // 定义更新移动元素样式的方法 - - var updateMovedElementStyle = function updateMovedElementStyle() { - restoreAttr(movedElement, 'style'); - restoreAttr(movedElement, 'class'); - - if (opt.clone) { - movedElement.parentElement.removeChild(movedElement); - } - }; - - store.updateMovedElementStyle = updateMovedElementStyle; // call hook beforeDrop - - if (opt.beforeDrop && opt.beforeDrop(store, opt) === false) { - return; - } // try to update moved element style - // 尝试更新移动元素样式 - - - if (!opt.updateMovedElementStyleManually) { - updateMovedElementStyle(); - } - - _edgeScroll.afterDrop(store, opt); - - opt.afterDrop && opt.afterDrop(store, opt); - }; // define the destroy function - // 定义销毁/退出的方法 - - - var destroy = function destroy() { - DragEventService.off(listenerElement, 'start', onMousedownOrTouchStart, { - touchArgs: [{ - passive: true - }] - }); - DragEventService.off(document, 'move', onMousemoveOrTouchMove, { - touchArgs: [{ - passive: false - }] - }); - DragEventService.off(window, 'end', onMouseupOrTouchEnd); - }; // - - - return { - destroy: destroy, - options: opt - }; - } // available options and default options value - // 可用选项和默认选项值 - - - var defaultOptions = { - ingoreTags: ['INPUT', 'TEXTAREA', 'SELECT', 'OPTGROUP', 'OPTION'], - undraggableClassName: 'undraggable', - minDisplacement: 10, - draggingClassName: 'dragging', - clone: false, - updateMovedElementStyleManually: false, - preventTextSelection: true, - edgeScrollTriggerMargin: 50, - edgeScrollSpeed: 0.35, - edgeScrollTriggerMode: 'top_left_corner' - }; // Info after event triggered. Created when mousedown or touchstart, destroied after mouseup or touchend. - // 事件触发后的相关信息. mousedown或touchstart时创建, mouseup或touchend后销毁. - - var initialStore = { - movedCount: 0 - }; // edge scroll - // 边缘滚动 - - var stopHorizontalScroll, stopVerticalScroll; - - _edgeScroll.afterMove = function (store, opt) { - if (!opt.edgeScroll) { - return; - } - - var margin = opt.edgeScrollTriggerMargin; - stopOldScrollAnimation(); // get triggerPoint. The point trigger edge scroll. - - var triggerPoint = { - x: store.mouse.clientX, - y: store.mouse.clientY - }; - - if (opt.edgeScrollTriggerMode === 'top_left_corner') { - var vp = getViewportPosition(store.movedElement); - triggerPoint = { - x: vp.x, - y: vp.y - }; - } // - - - var foundHorizontal, foundVertical, prevElement, horizontalDir, verticalDir; - var findInElements; - var cachedElementsFromPoint; // find x container - - var minScrollableDisplacement = 10; - - if (opt.edgeScrollSpecifiedContainerX) { - var containerX; - - if (typeof opt.edgeScrollSpecifiedContainerX === 'function') { - containerX = opt.edgeScrollSpecifiedContainerX(store, opt); - } else { - containerX = opt.edgeScrollSpecifiedContainerX; - } - - if (containerX) { - findInElements = [containerX]; - } - } - - if (!findInElements) { - findInElements = elementsFromPoint(triggerPoint.x, triggerPoint.y); - cachedElementsFromPoint = findInElements; - } - - var _iterator2 = _createForOfIteratorHelper$2(findInElements), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var itemEl = _step2.value; - - if (prevElement && !isDescendantOf(prevElement, itemEl)) { - // itemEl is being covered by other elements - // itemEl被其他元素遮挡 - continue; - } - - var t = minScrollableDisplacement; // min scrollable displacement. 最小可滚动距离, 小于此距离不触发滚动. - - if (!foundHorizontal) { - if (itemEl.scrollWidth > itemEl.clientWidth) { - var _vp = fixedGetViewportPosition(itemEl); - - if (triggerPoint.x <= _vp.left + margin) { - if (scrollableDisplacement(itemEl, 'left') > t && isScrollable(itemEl, 'x')) { - foundHorizontal = itemEl; - horizontalDir = 'left'; - } - } else if (triggerPoint.x >= _vp.left + itemEl.clientWidth - margin) { - if (scrollableDisplacement(itemEl, 'right') > t && isScrollable(itemEl, 'x')) { - foundHorizontal = itemEl; - horizontalDir = 'right'; - } - } - } - } - - if (foundHorizontal) { - break; - } - - prevElement = itemEl; - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - - prevElement = null; // find y container - - findInElements = null; - - if (opt.edgeScrollSpecifiedContainerY) { - var containerY; - - if (typeof opt.edgeScrollSpecifiedContainerY === 'function') { - containerY = opt.edgeScrollSpecifiedContainerY(store, opt); - } else { - containerY = opt.edgeScrollSpecifiedContainerY; - } - - if (containerY) { - findInElements = [containerY]; - } - } - - if (!findInElements) { - findInElements = cachedElementsFromPoint || elementsFromPoint(triggerPoint.x, triggerPoint.y); - } - - var _iterator3 = _createForOfIteratorHelper$2(findInElements), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _itemEl = _step3.value; - - if (prevElement && !isDescendantOf(prevElement, _itemEl)) { - // itemEl is being covered by other elements - // itemEl被其他元素遮挡 - continue; - } - - var _t = minScrollableDisplacement; // min scrollable displacement. 最小可滚动距离, 小于此距离不触发滚动. - - if (!foundVertical) { - if (_itemEl.scrollHeight > _itemEl.clientHeight) { - var _vp2 = fixedGetViewportPosition(_itemEl); - - if (triggerPoint.y <= _vp2.top + margin) { - if (scrollableDisplacement(_itemEl, 'up') > _t && isScrollable(_itemEl, 'y')) { - foundVertical = _itemEl; - verticalDir = 'up'; - } - } else if (triggerPoint.y >= _vp2.top + _itemEl.clientHeight - margin) { - if (scrollableDisplacement(_itemEl, 'down') > _t && isScrollable(_itemEl, 'y')) { - foundVertical = _itemEl; - verticalDir = 'down'; - } - } - } - } - - if (foundVertical) { - break; - } - - prevElement = _itemEl; - } // scroll - - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - if (foundHorizontal) { - if (horizontalDir === 'left') { - stopHorizontalScroll = scrollTo({ - x: 0, - element: foundHorizontal, - duration: scrollableDisplacement(foundHorizontal, 'left') / opt.edgeScrollSpeed - }); - } else { - stopHorizontalScroll = scrollTo({ - x: foundHorizontal.scrollWidth - foundHorizontal.clientWidth, - element: foundHorizontal, - duration: scrollableDisplacement(foundHorizontal, 'right') / opt.edgeScrollSpeed - }); - } - } - - if (foundVertical) { - if (verticalDir === 'up') { - stopVerticalScroll = scrollTo({ - y: 0, - element: foundVertical, - duration: scrollableDisplacement(foundVertical, 'up') / opt.edgeScrollSpeed - }); - } else { - stopVerticalScroll = scrollTo({ - y: foundVertical.scrollHeight - foundVertical.clientHeight, - element: foundVertical, - duration: scrollableDisplacement(foundVertical, 'down') / opt.edgeScrollSpeed - }); - } - } // is element scrollable in a direction - // 元素某方向是否可滚动 - - - function isScrollable(el, dir) { - var style = getComputedStyle(el); - var key = "overflow-".concat(dir); // document.documentElement is special - - var special = document.scrollingElement || document.documentElement; - - if (el === special) { - return style[key] === 'visible' || style[key] === 'auto' || style[key] === 'scroll'; - } - - return style[key] === 'auto' || style[key] === 'scroll'; - } // scrollable displacement of element in a direction - // 元素某方向可滚动距离 - - - function scrollableDisplacement(el, dir) { - if (dir === 'up') { - return el.scrollTop; - } else if (dir === 'down') { - return el.scrollHeight - el.scrollTop - el.clientHeight; - } else if (dir === 'left') { - return el.scrollLeft; - } else if (dir === 'right') { - return el.scrollWidth - el.scrollLeft - el.clientWidth; - } - } - - function fixedGetViewportPosition(el) { - var r = getViewportPosition(el); // document.documentElement is special - - var special = document.scrollingElement || document.documentElement; - - if (el === special) { - r.top = 0; - r.left = 0; - } - - return r; - } - }; - - _edgeScroll.afterDrop = function (store, opt) { - if (!opt.edgeScroll) { - return; - } - - stopOldScrollAnimation(); - }; // stop old scroll animation - // 结束之前的滚动动画 - - - function stopOldScrollAnimation() { - if (stopHorizontalScroll) { - stopHorizontalScroll(); - stopHorizontalScroll = null; - } - - if (stopVerticalScroll) { - stopVerticalScroll(); - stopVerticalScroll = null; - } - } - - function doDraggableDecision (_ref) { - var conditions = _ref.conditions, - doAction = _ref.doAction; - - // decision start ================================= - if (conditions['no closest'] === true) { - doAction('append to root'); - } else if (conditions['no closest'] === false) { - if (conditions['closest is top'] === true) { - if (conditions['on closest middle'] === true) { - doAction('insert before'); - } else if (conditions['on closest middle'] === false) { - if (conditions['at closest indent right'] === true) { - doAction('prepend'); - } else if (conditions['at closest indent right'] === false) { - if (conditions['closest is placeholder'] === true) { - doAction('insert after'); - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } - } - } else if (conditions['closest is top'] === false) { - if (conditions['on closest middle'] === true) { - if (conditions['at closest indent right'] === false) { - if (conditions['at closest left'] === false) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } else if (conditions['closest has next'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } else if (conditions['closest is placeholder'] === true) { - doAction('nothing'); - } - } else if (conditions['at closest left'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - doAction('nothing'); - } else if (conditions['no aboveBranch'] === false) { - doAction('after above'); - } - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } - } - } else if (conditions['at closest indent right'] === true) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - if (conditions['closest is top excluding placeholder'] === true) { - doAction('insert before'); - } else if (conditions['closest is top excluding placeholder'] === false) { - doAction('prepend'); - } - } - } else if (conditions['closest has next'] === false) { - doAction('prepend'); - } - } else if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - if (conditions['closest has prev'] === false) { - doAction('nothing'); - } else if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } - } else if (conditions['no aboveBranch'] === false) { - if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } else if (conditions['closest has prev'] === false) { - doAction('nothing'); - } - } - } - } - } else if (conditions['on closest middle'] === false) { - if (conditions['at closest indent right'] === false) { - if (conditions['at closest left'] === false) { - if (conditions['closest is placeholder'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } else if (conditions['closest is placeholder'] === true) { - doAction('nothing'); - } - } else if (conditions['at closest left'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === false) { - doAction('after above'); - } else if (conditions['no aboveBranch'] === true) { - doAction('nothing'); - } - } else if (conditions['closest is placeholder'] === false) { - if (conditions['closest has next'] === false) { - if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } else if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } - } else if (conditions['closest has next'] === true) { - if (conditions['closest has children excluding placeholder movingEl'] === true) { - doAction('prepend'); - } else if (conditions['closest has children excluding placeholder movingEl'] === false) { - doAction('insert after'); - } - } - } - } - } else if (conditions['at closest indent right'] === true) { - if (conditions['closest is placeholder'] === true) { - if (conditions['no aboveBranch'] === true) { - if (conditions['closest has prev'] === false) { - doAction('nothing'); - } else if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } - } else if (conditions['no aboveBranch'] === false) { - if (conditions['closest has prev'] === true) { - doAction('append to prev'); - } else if (conditions['closest has prev'] === false) { - doAction('nothing'); - } - } - } else if (conditions['closest is placeholder'] === false) { - doAction('prepend'); - } - } - } - } - } // decision end ================================= - - } - - function _createForOfIteratorHelper$3(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$4(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - - function _unsupportedIterableToArray$4(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$4(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4(o, minLen); } - - function _arrayLikeToArray$4(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - - function ownKeys$2(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$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - function makeTreeDraggable(treeEl) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - options = _objectSpread$2(_objectSpread$2({}, options), {}, { - treeEl: treeEl - }); - - var _draggableHelper = index(treeEl, { - triggerClassName: options.triggerClass, - triggerBySelf: options.triggerBySelf, - draggingClassName: options.draggingClass, - clone: options.cloneWhenDrag, - edgeScroll: options.edgeScroll, - edgeScrollTriggerMargin: options.edgeScrollTriggerMargin, - edgeScrollSpeed: options.edgeScrollSpeed, - edgeScrollTriggerMode: options.edgeScrollTriggerMode, - edgeScrollSpecifiedContainerX: options.edgeScrollSpecifiedContainerX, - edgeScrollSpecifiedContainerY: options.edgeScrollSpecifiedContainerY, - rtl: options.rtl, - preventTextSelection: options.preventTextSelection, - updateMovedElementStyleManually: true, - getMovedOrClonedElement: function getMovedOrClonedElement(directTriggerElement, store) { - // find closest branch from parents - var el = findParent(store.triggerElement, function (el) { - return hasClass(el, options.branchClass); - }, { - withSelf: true - }); - return el; - }, - beforeFirstMove: function beforeFirstMove(store, dhOptions) { - store.startTreeEl = treeEl; - store.dragBranchEl = store.movedElement; - store.startPath = options.getPathByBranchEl(store.movedOrClonedElement); - - if (options.beforeFirstMove && options.beforeFirstMove(store, dhOptions) === false) { - return false; - } - }, - beforeMove: function beforeMove(store, dhOptions) { - var updatePlaceholderIndent = function updatePlaceholderIndent() { - // set indent of placeholder - var placeholderPath = options.getPathByBranchEl(store.placeholder); - var placeholderNodeBack = store.placeholder.querySelector(".".concat(options.nodeBackClass)); - placeholderNodeBack.style[!options.rtl ? 'paddingLeft' : 'paddingRight'] = (placeholderPath.length - 1) * options.indent + 'px'; // remove tempChildren if empty - - if (store.tempChildren.children.length === 0) { - removeEl(store.tempChildren); - } - }; // first move - // 第一次移动 - - - if (store.movedCount === 0) { - // create placeholder - // 创建占位元素 - var placeholder = createElementFromHTML("\n
\n
\n
\n
\n
\n
\n ")); - insertAfter(placeholder, store.movedOrClonedElement); - store.placeholder = placeholder; - options.afterPlaceholderCreated(store); // create a tree children el to use when can't get childrenEl - - var tempChildren = document.createElement('DIV'); - addClass(tempChildren, options.childrenClass); - store.tempChildren = tempChildren; // update placeholder indent. update moved element style - - updatePlaceholderIndent(); - store.updateMovedElementStyle(); // skip first move - // 跳过第一次移动 - - return; - } // - - - store.updateMovedElementStyle(); // - - store.oneMoveStore = {}; // life cycle: one move - - var movingEl = store.movedElement; // branch - // find closest branch and hovering tree - - var _tree; - - var movingNode = movingEl.querySelector(".".concat(options.nodeClass)); // movingNodeOf and movingNodeRect are not always real. when RTL, there 'x' is top right. when draggingNodePositionMode is mouse, there x and y are mouse position. So don't calc them with their width or height. - // movingNodeOf 和 movingNodeRect并非一直如字面意义是movingNode真实坐标. RTL时, x坐标是右上角. draggingNodePositionMode是mouse时, x和y是鼠标坐标. - - var movingNodeOf = getOffset(movingNode); - var movingNodeRect = getBoundingClientRect(movingNode); - - if (options.draggingNodePositionMode === 'mouse') { - // use mouse position as dragging node position - var moveEvent = store.moveEvent; - movingNodeOf = { - x: moveEvent.pageX, - y: moveEvent.pageY - }; - movingNodeRect = { - x: moveEvent.clientX, - y: moveEvent.clientY - }; - } else if (options.rtl) { - movingNodeOf.x += movingNode.offsetWidth; - movingNodeRect.x += movingNode.offsetWidth; - } // find tree with elementsFromPoint - - - var found; - var firstElement; - - var _iterator = _createForOfIteratorHelper$3(elementsFromPoint(movingNodeRect.x, movingNodeRect.y)), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var itemEl = _step.value; - - if (!firstElement) { - firstElement = itemEl; - } - - if (hasClass(itemEl, options.treeClass)) { - found = itemEl; - break; - } - } // check if the found element is covered by other elements - - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (firstElement !== found && !isDescendantOf(firstElement, found)) { - found = null; - } - - _tree = found; - - if (!_tree) { - // out of tree or tree is covered by other elements - return; - } // check if target tree right - - - if (options.filterTargetTree(_tree, store, dhOptions) === false) { - return; - } - - store.targetTreeEl = _tree; // info ======================================== - // life cycle: one move - - var info = { - tree: function tree() { - return _tree; - }, - root: function root() { - return info.tree.querySelector(".".concat(options.childrenClass)); - }, - closestNode: function closestNode() { - var nodes = []; // all visible nodes sort by y - - var walkToGetNodes = function walkToGetNodes(branch) { - // - if (branch !== info.tree) { - var node = branch.querySelector(".".concat(options.nodeClass)); - - if (node && !isElementHidden(node)) { - nodes.push(node); - } - } // - - - var childrenEl = branch.querySelector(".".concat(options.childrenClass)); - - if (childrenEl) { - for (var i = 0; i < childrenEl.children.length; i++) { - var child = childrenEl.children[i]; - - if (child !== movingEl && hasClass(child, options.branchClass)) { - walkToGetNodes(child); - } - } - } - }; - - walkToGetNodes(info.tree); // - - if (nodes.length === 0) { - return; - } // - - - var found; - var t = binarySearch(nodes, function (node) { - return getOffset(node).y - movingNodeOf.y; - }, { - returnNearestIfNoHit: true - }); - - if (t.hit) { - found = t.value; - } else { - if (t.greater) { - found = nodes[t.index - 1] || t.value; - } else { - found = t.value; - } - } - - return found; - }, - closestNodeOffset: function closestNodeOffset() { - return getOffset(info.closestNode); - }, - closestBranch: function closestBranch() { - return findParent(info.closestNode, function (el) { - return hasClass(el, options.branchClass); - }); - }, - closestNext: function closestNext() { - var next = info.closestBranch.nextSibling; - - while (next) { - if (next !== movingEl && hasClass(next, options.branchClass) && !isElementHidden(next)) { - return next; - } - - next = next.nextSibling; - } - }, - closestPrev: function closestPrev() { - var prev = info.closestBranch.previousSibling; - - while (prev) { - if (prev !== movingEl && hasClass(prev, options.branchClass) && !isElementHidden(prev)) { - return prev; - } - - prev = prev.previousSibling; - } - }, - aboveBranch: function aboveBranch() { - // find above from branch to root - // closestBranch must be placeholder - if (info.closestBranch !== store.placeholder) { - return; - } - - if (conditions['closest has next']) { - return; - } // find placeholder prev or parent - - - var cur = info.closestBranch; - var prev = cur.previousSibling; - var found; - - while (prev) { - if (prev !== movingEl && hasClass(prev, options.branchClass) && !isElementHidden(prev)) { - cur = prev; - found = true; - break; - } - - prev = prev.previousSibling; - } - - if (!found) { - cur = findParent(cur, function (el) { - return hasClass(el, options.branchClass); - }); - } // - - - while (cur) { - var curNode = cur.querySelector(".".concat(options.nodeClass)); - - if (!options.rtl) { - if (getOffset(curNode).x <= movingNodeOf.x) { - break; - } - } else { - if (getOffset(curNode).x + curNode.offsetWidth >= movingNodeOf.x) { - break; - } - } - - var hasNextBranch = void 0; - var t = cur.nextSibling; - - while (t) { - if (t !== movingEl && t !== store.placeholder && hasClass(t, options.branchClass) && !isElementHidden(t)) { - hasNextBranch = true; - break; - } - - t = t.nextSibling; - } - - if (hasNextBranch) { - break; - } - - var parent = findParent(cur, function (el) { - return hasClass(el, options.branchClass); - }); - - if (!parent) { - break; - } - - cur = parent; - } - - return cur; - } - }; // conditions ======================================== - // life cycle: one move - - var conditions = { - 'no closest': function noClosest() { - return !info.closestNode; - }, - 'closest is top': function closestIsTop() { - return info.closestBranch === findNodeList(info.root.children, function (el) { - return el !== movingEl && !isElementHidden(el); - }); - }, - 'closest is top excluding placeholder': function closestIsTopExcludingPlaceholder() { - return info.closestBranch === findNodeList(info.root.children, function (el) { - return el !== movingEl && el !== store.placeholder && !isElementHidden(el); - }); - }, - 'on closest middle': function onClosestMiddle() { - return movingNodeOf.y < info.closestNodeOffset.y + info.closestNode.offsetHeight / 2; - }, - 'at closest indent right': function atClosestIndentRight() { - return movingNodeOf.x > info.closestNodeOffset.x + options.indent; - }, - 'at closest left': function atClosestLeft() { - return movingNodeOf.x < info.closestNodeOffset.x; - }, - 'closest is placeholder': function closestIsPlaceholder() { - return info.closestBranch === store.placeholder; - }, - 'no aboveBranch': function noAboveBranch() { - return !info.aboveBranch; - }, - 'closest has next': function closestHasNext() { - return info.closestNext; - }, - 'closest has prev': function closestHasPrev() { - return info.closestPrev; - }, - 'closest has children excluding placeholder movingEl': function closestHasChildrenExcludingPlaceholderMovingEl() { - var childrenEl = info.closestBranch.querySelector(".".concat(options.childrenClass)); - - if (childrenEl) { - return findNodeList(childrenEl.children, function (el) { - return el !== movingEl && el !== store.placeholder && !isElementHidden(el); - }); - } - } - }; // fix for rtl - - if (options.rtl) { - Object.assign(conditions, { - 'at closest indent right': function atClosestIndentRight() { - return movingNodeOf.x < info.closestNodeOffset.x + info.closestNode.offsetWidth - options.indent; - }, - // at indent left - 'at closest left': function atClosestLeft() { - return movingNodeOf.x > info.closestNodeOffset.x + info.closestNode.offsetWidth; - } // at right - - }); - } // convert conditions result to Boolean - - - Object.keys(conditions).forEach(function (key) { - var old = conditions[key]; - - conditions[key] = function () { - return Boolean(old.call(this)); - }; - }); // - - attachCache(info, info); - attachCache(conditions, conditions); - store.oneMoveStore.info = info; - store.oneMoveStore.conditions = conditions; // actions start ======================================== - - var doAction = function doAction(name) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - if (!store._doActionQueue) { - store._doActionQueue = Promise.resolve(); - } - - var queue = store._doActionQueue; - store._doActionQueue = queue.then( /*#__PURE__*/asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() { - var actionRecords, action, r; - return regenerator.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - // record tried actions in one move - if (!store.oneMoveStore.actionRecords) { - store.oneMoveStore.actionRecords = []; - } - - actionRecords = store.oneMoveStore.actionRecords; // - - action = actions[name]; - r = action.apply(void 0, args); - actionRecords.push(name); - _context.next = 7; - return r; - - case 7: - updatePlaceholderIndent(); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee); - }))); - }; - - var actions = { - 'nothing': function nothing() { - return asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() { - return regenerator.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - case "end": - return _context2.stop(); - } - } - }, _callee2); - }))(); - }, - // do nothing - 'append to root': function appendToRoot() { - return asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() { - return regenerator.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - // no closest branch, just append to root - if (options.isTargetTreeRootDroppable(store)) { - appendTo(store.placeholder, info.root); - } - - case 1: - case "end": - return _context3.stop(); - } - } - }, _callee3); - }))(); - }, - 'insert before': function insertBefore$1() { - return asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4() { - return regenerator.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - if (!options.isNodeParentDroppable(info.closestBranch, store.targetTreeEl)) { - _context4.next = 4; - break; - } - - insertBefore(store.placeholder, info.closestBranch); - _context4.next = 5; - break; - - case 4: - return _context4.abrupt("return", secondCase(getParentBranchByEl(info.closestBranch))); - - case 5: - case "end": - return _context4.stop(); - } - } - }, _callee4); - }))(); - }, - 'insert after': function insertAfter$1() { - var _arguments = arguments; - return asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5() { - var branch, moved, isFirstTriedAction; - return regenerator.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - branch = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : info.closestBranch; - - if (!options.isNodeParentDroppable(branch, store.targetTreeEl)) { - _context5.next = 5; - break; - } - - insertAfter(store.placeholder, branch); - _context5.next = 11; - break; - - case 5: - _context5.next = 7; - return secondCase(getParentBranchByEl(branch)); - - case 7: - moved = _context5.sent; - isFirstTriedAction = !store.oneMoveStore.actionRecords || store.oneMoveStore.actionRecords.length === 1; - - if (!(!moved && isFirstTriedAction)) { - _context5.next = 11; - break; - } - - return _context5.abrupt("return", thirdCase(branch)); - - case 11: - case "end": - return _context5.stop(); - } - } - }, _callee5); - }))(); - }, - prepend: function prepend() { - return asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6() { - return regenerator.wrap(function _callee6$(_context6) { - while (1) { - switch (_context6.prev = _context6.next) { - case 0: - if (!(info.closestBranch === store.placeholder)) { - _context6.next = 2; - break; - } - - return _context6.abrupt("return"); - - case 2: - if (!(options.ifNodeFolded(info.closestBranch, store) && !options.unfoldWhenDragover)) { - _context6.next = 6; - break; - } - - return _context6.abrupt("return", doAction('insert after', info.closestBranch)); - - case 6: - if (!options.isNodeDroppable(info.closestBranch, store.targetTreeEl)) { - _context6.next = 11; - break; - } - - _context6.next = 9; - return tryUnfoldAndPrepend(info.closestBranch); - - case 9: - _context6.next = 12; - break; - - case 11: - return _context6.abrupt("return", secondCase(info.closestBranch)); - - case 12: - case "end": - return _context6.stop(); - } - } - }, _callee6); - }))(); - }, - 'after above': function afterAbove() { - return asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7() { - return regenerator.wrap(function _callee7$(_context7) { - while (1) { - switch (_context7.prev = _context7.next) { - case 0: - if (!options.isNodeParentDroppable(info.aboveBranch, store.targetTreeEl)) { - _context7.next = 4; - break; - } - - insertAfter(store.placeholder, info.aboveBranch); - _context7.next = 5; - break; - - case 4: - return _context7.abrupt("return", secondCase(getParentBranchByEl(info.aboveBranch))); - - case 5: - case "end": - return _context7.stop(); - } - } - }, _callee7); - }))(); - }, - 'append to prev': function appendToPrev() { - return asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8() { - var childrenEl; - return regenerator.wrap(function _callee8$(_context8) { - while (1) { - switch (_context8.prev = _context8.next) { - case 0: - if (!(info.closestPrev === store.placeholder)) { - _context8.next = 2; - break; - } - - return _context8.abrupt("return"); - - case 2: - if (!options.ifNodeFolded(info.closestPrev, store)) { - _context8.next = 6; - break; - } - - return _context8.abrupt("return", doAction('insert after', info.closestPrev)); - - case 6: - if (!options.isNodeDroppable(info.closestPrev, store.targetTreeEl)) { - _context8.next = 13; - break; - } - - _context8.next = 9; - return unfoldAndGetChildrenEl(info.closestPrev); - - case 9: - childrenEl = _context8.sent; - appendTo(store.placeholder, childrenEl); - _context8.next = 14; - break; - - case 13: - return _context8.abrupt("return", secondCase(info.closestPrev)); - - case 14: - case "end": - return _context8.stop(); - } - } - }, _callee8); - }))(); - } - }; // second case for actions, when target position not droppable - // return true if moved - - var secondCase = /*#__PURE__*/function () { - var _ref2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9(branchEl) { - var targetEl; - return regenerator.wrap(function _callee9$(_context9) { - while (1) { - switch (_context9.prev = _context9.next) { - case 0: - if (!branchEl) { - _context9.next = 5; - break; - } - - targetEl = options._findClosestDroppablePosition(branchEl, store.targetTreeEl); - - if (!targetEl) { - _context9.next = 5; - break; - } - - insertAfter(store.placeholder, targetEl); - return _context9.abrupt("return", true); - - case 5: - case "end": - return _context9.stop(); - } - } - }, _callee9); - })); - - return function secondCase(_x) { - return _ref2.apply(this, arguments); - }; - }(); // when action is after, first case and second case invalid, try prepend - // 当操作是'after', 第一种第二种情况无效时, 尝试prepend - - - var thirdCase = /*#__PURE__*/function () { - var _ref3 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10(branchEl) { - return regenerator.wrap(function _callee10$(_context10) { - while (1) { - switch (_context10.prev = _context10.next) { - case 0: - if (!(!options.ifNodeFolded(branchEl, store) && options.isNodeDroppable(branchEl, store.targetTreeEl))) { - _context10.next = 3; - break; - } - - _context10.next = 3; - return tryUnfoldAndPrepend(branchEl); - - case 3: - case "end": - return _context10.stop(); - } - } - }, _callee10); - })); - - return function thirdCase(_x2) { - return _ref3.apply(this, arguments); - }; - }(); - - var unfoldAndGetChildrenEl = /*#__PURE__*/function () { - var _ref4 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee11(branch) { - var childrenEl; - return regenerator.wrap(function _callee11$(_context11) { - while (1) { - switch (_context11.prev = _context11.next) { - case 0: - _context11.next = 2; - return options.unfoldTargetNodeByEl(branch, store); - - case 2: - childrenEl = branch.querySelector(".".concat(options.childrenClass)); - - if (!childrenEl) { - childrenEl = store.tempChildren; - appendTo(childrenEl, branch); - } - - return _context11.abrupt("return", childrenEl); - - case 5: - case "end": - return _context11.stop(); - } - } - }, _callee11); - })); - - return function unfoldAndGetChildrenEl(_x3) { - return _ref4.apply(this, arguments); - }; - }(); - - var tryUnfoldAndPrepend = /*#__PURE__*/function () { - var _ref5 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee13(branchEl) { - var func, oneMoveStore; - return regenerator.wrap(function _callee13$(_context13) { - while (1) { - switch (_context13.prev = _context13.next) { - case 0: - func = /*#__PURE__*/function () { - var _ref6 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee12() { - var childrenEl; - return regenerator.wrap(function _callee12$(_context12) { - while (1) { - switch (_context12.prev = _context12.next) { - case 0: - _context12.next = 2; - return unfoldAndGetChildrenEl(branchEl); - - case 2: - childrenEl = _context12.sent; - prependTo(store.placeholder, childrenEl); - - case 4: - case "end": - return _context12.stop(); - } - } - }, _callee12); - })); - - return function func() { - return _ref6.apply(this, arguments); - }; - }(); - - if (!options.ifNodeFolded(branchEl, store)) { - _context13.next = 6; - break; - } - - // delay if node folded - oneMoveStore = store.oneMoveStore; - setTimeout(function () { - // check if expired - if (oneMoveStore === store.oneMoveStore) { - func(); - } - }, options.unfoldWhenDragoverDelay); - _context13.next = 8; - break; - - case 6: - _context13.next = 8; - return func(); - - case 8: - case "end": - return _context13.stop(); - } - } - }, _callee13); - })); - - return function tryUnfoldAndPrepend(_x4) { - return _ref5.apply(this, arguments); - }; - }(); // actions end ======================================== - - - doDraggableDecision({ - options: options, - event: store.moveEvent, - store: store, - opt: dhOptions, - info: info, - conditions: conditions, - actions: actions, - doAction: doAction - }); - }, - afterMove: function afterMove(store, dhOptions) { - options.afterMove && options.afterMove(store, dhOptions); - }, - beforeDrop: function () { - var _beforeDrop = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee14(store, dhOptions) { - var endEvent, movingEl, placeholder, tempChildren, movedCount, targetTreeEl, startTreeEl, maskTree, maskTree2, pathChanged, getTargetPath; - return regenerator.wrap(function _callee14$(_context14) { - while (1) { - switch (_context14.prev = _context14.next) { - case 0: - getTargetPath = function _getTargetPath() { - // example - // startPath placeholderPath - // [0] [1] - // [0] [1, 0] - // [3, 1] [3, 3] - // [3, 1] [3, 3, 5] - // above targetPaths should be [0], [0, 0] [3, 2] [3, 2, 5] - var startTree = store.startTree, - targetTree = store.targetTree, - startPath = store.startPath, - placeholderPath = store.placeholderPath; - var targetPath = placeholderPath.slice(0); - - if (options.cloneWhenDrag !== true) { - if (startTree === targetTree) { - if (startPath.length <= targetPath.length) { - var sw = startPath.slice(0, startPath.length - 1); // without end - - var tw = targetPath.slice(0, sw.length); // same length with sw - - if (sw.toString() === tw.toString()) { - var endIndex = sw.length; - - if (startPath[endIndex] < targetPath[endIndex]) { - targetPath[endIndex] -= 1; - } else if (startPath[endIndex] === targetPath[endIndex]) ; - } - } - } - } - - return targetPath; - }; - - endEvent = store.endEvent; - movingEl = store.movedElement; // branch - - placeholder = store.placeholder, tempChildren = store.tempChildren, movedCount = store.movedCount, targetTreeEl = store.targetTreeEl, startTreeEl = store.startTreeEl; // use mask tree to avoid flick caused by DOM update in short time - // 复制 targetTreeEl 作为遮罩, 避免短时间内更新DOM引起的闪烁 - - if (targetTreeEl) { - // No targetTreeEl mean no valid move. - // targetTreeEl不存在意味着没有有效移动. - // create mask tree - maskTree = targetTreeEl.cloneNode(true); - targetTreeEl.style.display = 'none'; - insertAfter(maskTree, targetTreeEl); - - if (startTreeEl !== targetTreeEl) { - maskTree2 = startTreeEl.cloneNode(true); - startTreeEl.style.display = 'none'; - insertAfter(maskTree2, startTreeEl); - } // - - - store.placeholderPath = options.getPathByBranchEl(placeholder); - store.targetPath = getTargetPath(); - pathChanged = targetTreeEl === startTreeEl && store.targetPath.toString() !== store.startPath.toString(); - store.pathChangePrevented = false; - - if (options.beforeDrop && options.beforeDrop(pathChanged, store, dhOptions) === false) { - pathChanged = false; - store.pathChangePrevented = false; - } - - store.pathChanged = pathChanged; - } // destroy placeholder and tempChildren - - - removeEl(placeholder); - - if (tempChildren) { - removeEl(tempChildren); - } - - store.updateMovedElementStyle(); // - - _context14.next = 10; - return options.afterDrop(store, dhOptions); - - case 10: - if (!maskTree) { - _context14.next = 16; - break; - } - - _context14.next = 13; - return waitTime(0); - - case 13: - removeEl(maskTree); - targetTreeEl.style.display = 'block'; - - if (maskTree2) { - removeEl(maskTree2); - startTreeEl.style.display = 'block'; - } - - case 16: - case "end": - return _context14.stop(); - } - } - }, _callee14); - })); - - function beforeDrop(_x5, _x6) { - return _beforeDrop.apply(this, arguments); - } - - return beforeDrop; - }() - }), - destroy = _draggableHelper.destroy, - draggableHelperOptions = _draggableHelper.options; - - return { - destroy: destroy, - options: options, - optionsUpdated: optionsUpdated - }; - - function getParentBranchByEl(el) { - return findParent(el, function (el) { - if (hasClass(el, options.branchClass)) { - return true; - } - - if (hasClass(el, options.rootClass)) { - return 'break'; - } - }); - } - - function optionsUpdated() { - Object.assign(draggableHelperOptions, { - triggerClassName: options.triggerClass, - triggerBySelf: options.triggerBySelf, - draggingClassName: options.draggingClass, - clone: options.cloneWhenDrag, - // edgeScroll - edgeScroll: options.edgeScroll, - edgeScrollTriggerMargin: options.edgeScrollTriggerMargin, - edgeScrollSpeed: options.edgeScrollSpeed, - edgeScrollTriggerMode: options.edgeScrollTriggerMode, - // - rtl: options.rtl, - preventTextSelection: options.preventTextSelection - }); - } - } - - function isElementHidden(el) { - return el.offsetWidth === 0 && el.offsetHeight === 0; - } - - function _createForOfIteratorHelper$4(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$5(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } - - function _unsupportedIterableToArray$5(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$5(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$5(o, minLen); } - - function _arrayLikeToArray$5(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - var treesStore = {}; - var script = { - props: { - triggerClass: { - type: [String, Array], - default: 'tree-node' - }, - triggerBySelf: { - type: Boolean - }, - draggable: { - type: [Boolean, Function], - default: true - }, - droppable: { - type: [Boolean, Function], - default: true - }, - eachDraggable: { - type: [Function] - }, - // type: [Boolean, Function] - eachDroppable: { - type: [Function] - }, - // type: [Boolean, Function] - ondragstart: { - type: Function - }, - ondragend: { - type: Function - }, - unfoldWhenDragover: { - type: Boolean, - default: true - }, - unfoldWhenDragoverDelay: { - type: Number, - default: 30 - }, - draggingNodePositionMode: { - type: String, - default: 'top_left_corner' - }, - // top_left_corner, mouse - edgeScroll: { - type: Boolean - }, - edgeScrollTriggerMargin: { - type: Number, - default: 50 - }, - edgeScrollSpeed: { - type: Number, - default: 0.35 - }, - edgeScrollTriggerMode: { - type: String, - default: 'top_left_corner' - }, - edgeScrollSpecifiedContainerX: {}, - // HTMLElement || ((store) => HTMLElement) - edgeScrollSpecifiedContainerY: {}, - // HTMLElement || ((store) => HTMLElement) - preventTextSelection: { - type: Boolean, - default: true - } - }, - // components: {}, - data: function data() { - return { - treesStore: treesStore - }; - }, - // computed: {}, - // watch: {}, - methods: { - _Draggable_unfoldTargetNodeByEl: function _Draggable_unfoldTargetNodeByEl(branchEl, store) { - var targetTree = store.targetTree; - var path = targetTree.getPathByBranchEl(branchEl); - var node = targetTree.getNodeByPath(path); - targetTree.unfold && targetTree.unfold(node, path); - return new Promise(function (resolve, reject) { - targetTree.$nextTick(function () { - resolve(); - }); - }); - }, - isNodeDraggable: function isNodeDraggable(node, path) { - var store = this.treesStore.store; - var allNodes = this.getAllNodesByPath(path); - allNodes.unshift(this.rootNode); - - var _iterator = _createForOfIteratorHelper$4(iterateAll(allNodes, { - reverse: true - })), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _step$value = _step.value, - _node = _step$value.value, - index = _step$value.index; - var currentPath = path.slice(0, index + 1); - var draggableOpt = _node.$draggable !== undefined ? _node.$draggable : this.eachDraggable; - var draggable = resolveValueOrGettter(draggableOpt, [currentPath, this, store]); - - if (draggable === undefined) { - continue; - } else { - return draggable; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return true; - }, - isNodeDroppable: function isNodeDroppable(node, path) { - var store = this.treesStore.store; - var allNodes = this.getAllNodesByPath(path); - allNodes.unshift(this.rootNode); - var droppableFinal, resolved; - - var _iterator2 = _createForOfIteratorHelper$4(iterateAll(allNodes, { - reverse: true - })), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var _step2$value = _step2.value, - _node2 = _step2$value.value, - index = _step2$value.index; - var currentPath = path.slice(0, index + 1); - var droppableOpt = _node2.$droppable !== undefined ? _node2.$droppable : this.eachDroppable; - var droppable = resolveValueOrGettter(droppableOpt, [currentPath, this, store]); - - if (droppable === undefined) { - continue; - } else { - droppableFinal = droppable; - resolved = true; - break; - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - - if (!resolved) { - droppableFinal = true; - } - - if (this._internal_hook_isNodeDroppable) { - return this._internal_hook_isNodeDroppable({ - droppableFinal: droppableFinal, - node: node, - path: path, - store: store - }); - } - - return droppableFinal; - }, - // override - getPathByBranchEl: function getPathByBranchEl(branchEl) { - var store = this.treesStore.store; - - var getAttrPath = function getAttrPath(el) { - var pathStr = el.getAttribute('data-tree-node-path'); - - if (pathStr) { - return pathStr.split(',').map(function (v) { - return parseInt(v); - }); - } - }; - - var path = getAttrPath(branchEl); - - if (path) { - return path; - } // placeholder path - - - var parentPath; - findParent(branchEl, function (el) { - if (hasClass(el, 'tree-root')) { - parentPath = []; - return true; - } - - if (hasClass(el, 'tree-branch')) { - parentPath = getAttrPath(el); - return true; - } - }); - var index = 0; - - var _iterator3 = _createForOfIteratorHelper$4(iterateAll(branchEl.parentElement.children)), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _step3$value = _step3.value, - el = _step3$value.value, - index2 = _step3$value.index; - - if (hasClass(el, 'tree-branch') || hasClass(el, 'tree-placeholder')) { - if (el === branchEl) { - break; - } - - index++; - } - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - return [].concat(toConsumableArray(parentPath), [index]); - } - }, - // created() {}, - mounted: function mounted() { - var _this = this; - - var options = this._draggableOptions = { - indent: this.indent, - triggerClass: this.triggerClass, - triggerBySelf: this.triggerBySelf, - unfoldWhenDragover: this.unfoldWhenDragover, - unfoldWhenDragoverDelay: this.unfoldWhenDragoverDelay, - draggingNodePositionMode: this.draggingNodePositionMode, - cloneWhenDrag: this.cloneWhenDrag, - edgeScroll: this.edgeScroll, - edgeScrollTriggerMargin: this.edgeScrollTriggerMargin, - edgeScrollSpeed: this.edgeScrollSpeed, - edgeScrollTriggerMode: this.edgeScrollTriggerMode, - edgeScrollSpecifiedContainerX: this.edgeScrollSpecifiedContainerX, - edgeScrollSpecifiedContainerY: this.edgeScrollSpecifiedContainerY, - rtl: this.rtl, - preventTextSelection: this.preventTextSelection, - treeClass: 'he-tree', - rootClass: 'tree-root', - childrenClass: 'tree-children', - branchClass: 'tree-branch', - nodeClass: 'tree-node', - nodeBackClass: 'tree-node-back', - placeholderClass: 'tree-placeholder', - placeholderNodeBackClass: 'tree-placeholder-node-back', - placeholderNodeClass: 'tree-placeholder-node', - draggingClass: 'dragging', - placeholderId: "he_tree_drag_placeholder", - ifNodeFolded: function ifNodeFolded(branchEl, store) { - var targetTree = store.targetTree; - var node = targetTree.getNodeByBranchEl(branchEl); - return node.$folded; - }, - isTargetTreeRootDroppable: function isTargetTreeRootDroppable(store) { - var droppable = resolveValueOrGettter(store.targetTree.rootNode.$droppable, [store.targetTree, store]); - - if (droppable !== undefined) { - return droppable; - } - - return true; - }, - unfoldTargetNodeByEl: function unfoldTargetNodeByEl() { - return _this._Draggable_unfoldTargetNodeByEl.apply(_this, arguments); - }, - isNodeParentDroppable: function isNodeParentDroppable(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var parentPath = arrayWithoutEnd(path, 1); - var parent = tree.getNodeByPath(parentPath); - return tree.isNodeDroppable(parent, parentPath); - }, - isNodeDroppable: function isNodeDroppable(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var node = tree.getNodeByPath(path); - return tree.isNodeDroppable(node, path); - }, - _findClosestDroppablePosition: function _findClosestDroppablePosition(branchEl, treeEl) { - var tree = _this.getTreeVmByTreeEl(treeEl); - - var path = tree.getPathByBranchEl(branchEl); - var findPath = arrayWithoutEnd(path, 1); - var cur = path; - - var _iterator4 = _createForOfIteratorHelper$4(tree.iteratePath(findPath, { - reverse: true - })), - _step4; - - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var _step4$value = _step4.value, - node = _step4$value.node, - _path = _step4$value.path; - - if (tree.isNodeDroppable(node, _path)) { - return tree.getBranchElByPath(cur); - } else { - cur = _path; - } - } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); - } - - if (tree.isNodeDroppable(_this.rootNode, [])) { - return tree.getBranchElByPath(cur); - } - }, - afterPlaceholderCreated: function afterPlaceholderCreated(store) { - store.startTree.$emit('afterPlaceholderCreated', store); - store.startTree.$emit('after-placeholder-created', store); - }, - getPathByBranchEl: function getPathByBranchEl(branchEl) { - return _this.getPathByBranchEl(branchEl); - }, - beforeFirstMove: function beforeFirstMove(store) { - _this.treesStore.store = store; - store.startTree = _this.getTreeVmByTreeEl(store.startTreeEl); - var draggable = resolveValueOrGettter(store.startTree.draggable, [store.startTree, store]); - - if (!draggable) { - return false; - } - - var startTree = store.startTree, - dragBranchEl = store.dragBranchEl, - startPath = store.startPath; - store.dragNode = startTree.getNodeByPath(startPath); - - if (_this.cloneWhenDrag) { - store.dragNode = cloneTreeData(store.dragNode); - } - - if (!startTree.isNodeDraggable(store.dragNode, startPath)) { - return false; - } - - if (startTree.hasHook('ondragstart') && startTree.executeHook('ondragstart', [startTree, store]) === false) { - return false; - } - - store.startTree.$emit('before-first-move', store); - store.startTree.$emit('drag', store); - - _this.$root.$emit('he-tree-drag', store); - }, - filterTargetTree: function filterTargetTree(targetTreeEl, store) { - var targetTree = _this.getTreeVmByTreeEl(targetTreeEl); - - var startTree = store.startTree; - - if (startTree !== targetTree) { - if (_this._internal_hook_filterTargetTree) { - if (_this._internal_hook_filterTargetTree(targetTree, store) === false) { - return false; - } - } else { - return false; - } - } - - var targetTreeDroppable = resolveValueOrGettter(targetTree.droppable, [targetTree, store]); - - if (!targetTreeDroppable) { - return false; - } - - store.targetTree = targetTree; - - if (!resolveValueOrGettter(store.startTree === store.targetTree) && resolveValueOrGettter(_this._Draggable_unfoldTargetNode, [false, _this.treeData]) !== _this.rootNode.children) { - return false; - } - }, - afterMove: function afterMove(store) { - store.startTree.$emit('after-move', store); - }, - beforeDrop: function beforeDrop(pathChanged, store) { - var targetTree = store.targetTree; - - if (targetTree.hasHook('ondragend') && targetTree.executeHook('ondragend', [targetTree, store]) === false) { - return false; - } - - _this.$root.$emit('he-tree-before-drop', store); - }, - afterDrop: function afterDrop(store, t) { - if (store.pathChanged) { - var startTree = store.startTree, - targetTree = store.targetTree, - startPath = store.startPath, - dragNode = store.dragNode; - var targetPath = store.targetPath; - - if (_this.cloneWhenDrag !== true) { - // remove from start position - var startParentPath = arrayWithoutEnd(startPath, 1); - var startParent = startTree.getNodeByPath(startParentPath); - var startSiblings = startParentPath.length === 0 ? startTree.treeData : startParent.children; - var startIndex = arrayLast(startPath); - startSiblings.splice(startIndex, 1); - } // insert to target position - - - var targetParentPath = arrayWithoutEnd(targetPath, 1); - var targetParent = targetTree.getNodeByPath(targetParentPath); - var targetSiblings; - - if (targetParentPath.length === 0) { - targetSiblings = targetTree.treeData; - } else { - if (!targetParent.children) { - _this.$set(targetParent, 'children', []); - } - - targetSiblings = targetParent.children; - } - - var targetIndex = arrayLast(targetPath); - targetSiblings.splice(targetIndex, 0, dragNode); // emit event - - startTree.$emit('input', startTree.treeData); - startTree.$emit('change', store); - targetTree.$emit('drop', store); - - _this.$root.$emit('he-tree-drop', store); - - if (targetTree !== startTree) { - targetTree.$emit('input', targetTree.treeData); - targetTree.$emit('change', store); - } - - return new Promise(function (resolve, reject) { - targetTree.$nextTick(function () { - resolve(); - }); - }); - } - } - }; - - var _makeTreeDraggable_obj = this._makeTreeDraggable_obj = makeTreeDraggable(this.$el, options); // watch props and update options - - - ['indent', 'triggerClass', 'triggerBySelf', 'unfoldWhenDragover', 'unfoldWhenDragoverDelay', 'draggingNodePositionMode', 'cloneWhenDrag', 'edgeScroll', 'edgeScrollTriggerMargin', 'edgeScrollSpeed', 'edgeScrollTriggerMode', 'edgeScrollSpecifiedContainerY', 'edgeScrollSpecifiedContainerY', 'rtl', 'preventTextSelection'].forEach(function (name) { - _this.$watch(name, function (value) { - _makeTreeDraggable_obj.options[name] = value; - - _makeTreeDraggable_obj.optionsUpdated(); - }); - }); - } - }; - - /* script */ - var __vue_script__$1 = script; - /* template */ - - /* style */ - - var __vue_inject_styles__$1 = undefined; - /* scoped */ - - var __vue_scope_id__$1 = undefined; - /* module identifier */ - - var __vue_module_identifier__$1 = undefined; - /* functional template */ - - var __vue_is_functional_template__$1 = undefined; - /* style inject */ - - /* style inject SSR */ - - /* style inject shadow dom */ - - var __vue_component__$1 = /*#__PURE__*/normalizeComponent({}, __vue_inject_styles__$1, __vue_script__$1, __vue_scope_id__$1, __vue_is_functional_template__$1, __vue_module_identifier__$1, false, undefined, undefined, undefined); - - exports.Check = check; - exports.Draggable = __vue_component__$1; - exports.Fold = fold; - exports.Tree = __vue_component__; - exports.cloneTreeData = cloneTreeData; - exports.foldAll = foldAll; - exports.getPureTreeData = getPureTreeData; - exports.unfoldAll = unfoldAll; - exports.walkTreeData = walkTreeData$1; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); diff --git a/dist/he-tree-vue.min.js b/dist/he-tree-vue.min.js deleted file mode 100644 index 99eb4fb..0000000 --- a/dist/he-tree-vue.min.js +++ /dev/null @@ -1,25 +0,0 @@ -/*! - * he-tree-vue v2.0.11.beta.3 - * (c) phphe (https://github.com/phphe) - * Homepage: https://he-tree-vue.phphe.com - * Released under the MIT License. - */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],t):t((e=e||self).heTreeVue={},e.Vue)}(this,(function(e,t){"use strict";t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t;var r=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0;--o){var a=this.tryEntries[o],i=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var l=r.call(a,"catchLoc"),c=r.call(a,"finallyLoc");if(l&&c){if(this.prev=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),S(r),s}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;S(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:E(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),s}},e}(e.exports);try{regeneratorRuntime=t}catch(e){Function("r","regeneratorRuntime = r")(t)}})),v=g.mark(C);function y(e){if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(e=function(e,t){if(!e)return;if("string"==typeof e)return m(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return m(e,t)}(e))){var t=0,r=function(){};return{s:r,n:function(){return t>=e.length?{done:!0}:{done:!1,value:e[t++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,o,a=!0,i=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return a=e.done,e},e:function(e){i=!0,o=e},f:function(){try{a||null==n.return||n.return()}finally{if(i)throw o}}}}function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r0&&void 0!==arguments[0]?arguments[0]:8,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r="",n=0;n1&&void 0!==y[1]?y[1]:{}).reverse){g.next=30;break}if(null==e.length){g.next=14;break}r=0;case 4:if(!(r=0)){g.next=40;break}if(s={value:e[c],index:c},t.exclude&&t.exclude(s)){g.next=37;break}return g.next=37,s;case 37:c--,g.next=32;break;case 40:g.next=58;break;case 42:if(!x(e)){g.next=57;break}(u=Object.keys(e)).reverse(),d=0,f=u;case 46:if(!(d2&&void 0!==arguments[2]?arguments[2]:"children",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=b(e)?e:[e],a=function e(){p(this,e)},i=function e(o,i,c){n.reverse&&(o=o.slice()).reverse();for(var s=o.length,u=0;u0&&void 0!==arguments[0]?arguments[0]:[];p(this,e),this.childrenKey="children",this.data=t}return h(e,[{key:"iteratePath",value:g.mark((function e(t){var r,n,o,a,i,c,s,u,d,f,h,p,v,m,b,x,S,w=arguments;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=w.length>1&&void 0!==w[1]?w[1]:{},n=this.childrenKey,o=this.rootChildren,r.reverse){e.next=29;break}a=[],i=o,c=y(t),e.prev=6,c.s();case 8:if((s=c.n()).done){e.next=19;break}return u=s.value,d=[].concat(l(a),[u]),f=i[u],e.next=14,{path:d,node:f};case 14:a=d,i=f[n];case 17:e.next=8;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(6),c.e(e.t0);case 24:return e.prev=24,c.f(),e.finish(24);case 27:e.next=49;break;case 29:(h=l(this.iteratePath(t,Object.assign(Object.assign({},r),{reverse:!1})))).reverse(),p=y(h),e.prev=32,p.s();case 34:if((v=p.n()).done){e.next=41;break}return m=v.value,b=m.path,x=m.node,S=b,e.next=39,{path:S,node:x};case 39:e.next=34;break;case 41:e.next=46;break;case 43:e.prev=43,e.t1=e.catch(32),p.e(e.t1);case 46:return e.prev=46,p.f(),e.finish(46);case 49:case"end":return e.stop()}}),e,this,[[6,21,24,27],[32,43,46,49]])}))},{key:"getAllNodes",value:function(e){var t,r=[],n=y(this.iteratePath(e));try{for(n.s();!(t=n.n()).done;){var o=t.value.node;r.push(o)}}catch(e){n.e(e)}finally{n.f()}return r}},{key:"getNode",value:function(e){return k(this.getAllNodes(e))}},{key:"getNodeIndexAndParent",value:function(e){var t=e.slice(),r=t.pop();return{parent:this.getNode(t),index:r,parentPath:t}}},{key:"getNodeParent",value:function(e){return this.getNodeIndexAndParent(e).parent}},{key:"setPathNode",value:function(e,t){if(null==e||0===e.length)this.data=t;else{var r=this.childrenKey,n=this.rootChildren,o=this.getNodeIndexAndParent(e),a=o.parent,i=o.index;(1===e.length?n:a[r])[i]=t}}},{key:"removeNode",value:function(e){var t=this.childrenKey,r=this.rootChildren,n=this.getNodeIndexAndParent(e),o=n.parent,a=n.index,i=1===e.length?r:o[t],l=i[a];return i.splice(a,1),l}},{key:"walk",value:function(e,t){var r=this.childrenKey,n=this.data;return O(n,e,r,t)}},{key:"clone",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=this.childrenKey,n=new e;return this.walk((function(e,o,a,i){var l=Object.assign({},e);l[r]&&(l[r]=[]),t.afterNodeCreated&&t.afterNodeCreated(l,{oldNode:e,index:o,parent:a,path:i}),n.setPathNode(i,l)})),n.data}},{key:"rootChildren",get:function(){var e=this.childrenKey,t=this.data;return b(t)?t:t[e]}}]),e}();function D(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return S(e)?e.apply(void 0,l(t)):e}function _(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.childNodes.length>1?t.childNodes:t.childNodes[0]}function M(e,t){for(;;){if(null==e.parentElement)return!1;if(e.parentElement===t)return!0;e=e.parentElement}}function j(e){if(null!==e.parentNode)return e.parentNode.removeChild(e)}function $(e){var t=A(e),r=function(){if("undefined"!=typeof pageYOffset)return{top:pageYOffset,left:pageXOffset};var e=document.body,t=document.documentElement;return{top:(t=t.clientHeight?t:e).scrollTop,left:t.scrollLeft}}();return{x:t.left+r.left,y:t.top+r.top}}function A(e){var t=e.getBoundingClientRect(),r=t.top-document.documentElement.clientTop,n=t.bottom,o=t.left-document.documentElement.clientLeft,a=t.right;return{top:r,right:a,bottom:n,left:o,width:t.width||a-o,height:t.height||n-r,x:o,y:r}}var L=A;function F(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r&&r.withSelf?e:e.parentElement;n;){var o=t(n);if("break"===o)return;if(o)return n;n=n.parentElement}}function I(e,t){e["original_".concat(t)]=e.getAttribute(t)}function H(e,t){var r=e["original_".concat(t)];null==r?e.removeAttribute(t):e.setAttribute(t,r)}function Y(e,t){return e.classList?e.classList.contains(t):new RegExp("(^| )"+t+"( |$)","gi").test(e.className)}function W(e,t){Y(e,t)||(e.classList?e.classList.add(t):e.className+=" "+t)}function X(e,t,r){for(var n=arguments.length,o=new Array(n>3?n-3:0),a=3;a3?n-3:0),a=3;a2&&void 0!==arguments[2]?arguments[2]:{},o=C(e,{reverse:n.reverse}),a=y(o);try{for(a.s();!(r=a.n()).done;){var i=r.value,l=i.value,c=i.index;if(t(l,c))return l}}catch(e){a.e(e)}finally{a.f()}}function V(e,t){var r=[e,t];return(document.elementsFromPoint||document.msElementsFromPoint||function(e,t){var r=[],n=void 0;do{n!==document.elementFromPoint(e,t)?(n=document.elementFromPoint(e,t),r.push(n),n.style.pointerEvents="none"):n=!1}while(n);return r.forEach((function(e){return e.style.pointerEvents="all"})),r}).apply(document,r)}function q(e){e.element||(e.element=document.scrollingElement||document.documentElement),null==e.duration&&(e.duration=0);var t,r=e.x,n=e.y,o=e.duration,a=e.element,i=0,l=a.scrollTop,c=n-l,s=a.scrollLeft,u=r-s,d=+new Date;return function h(){if(!e.beforeEveryFrame||!1!==e.beforeEveryFrame(i)){var p=(new Date).getTime()-d;null!=n&&(a.scrollTop=parseInt(f(l,c,p,o))),null!=r&&(a.scrollLeft=parseInt(f(s,u,p,o))),p2&&void 0!==arguments[2]?arguments[2]:{},a=o=Object.assign({start:0,end:e.length-1,maxTimes:1e3},o),i=a.start,l=a.end,c=o,s=c.returnNearestIfNoHit,u=c.maxTimes;null==i&&(i=0,l=e.length-1);for(var d,f=0;i>=0&&i<=l;){if(f>=u)throw Error("binarySearch: loop times is over ".concat(u,", you can increase the limit."));if((d=t(n=e[r=Math.floor((l-i)/2+i)],f))>0)l=r-1;else{if(!(d<0))return{index:r,value:n,count:f+1,hit:!0};i=r+1}f++}return s?{index:r,value:n,count:f+1,hit:!1,greater:d>0}:null}function Z(e,t){return new Promise((function(r,n){setTimeout((function(){t&&t(),r()}),e)}))}var ee=function(){function e(){p(this,e),this.store={}}return h(e,[{key:"has",value:function(e){return this.store.hasOwnProperty(e)}},{key:"remember",value:function(e,t){return this.has(e)||(this.store[e]={value:t()}),this.store[e].value}},{key:"forget",value:function(e){e?this.has(e)&&delete this.store[e]:this.store={}}}]),e}();function te(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new ee,n=function(n){var o=t[n];Object.defineProperty(e,n,{get:function(){var e=this;return r.remember(n,(function(){return o.call(e)}))}})};for(var o in t)n(o)} -/*! - * vue-functions v2.0.6 - * (c) phphe (https://github.com/phphe) - * Homepage: undefined - * Released under the MIT License. - */var re={methods:{_getNonPropHooksByName:function(e){if(this._hooks)return this._hooks[e]},addHook:function(e,t){this._getNonPropHooksByName(e)||(this._hooks||(this._hooks={}),this._hooks[e]||(this._hooks[e]=[])),this._hooks[e].push(t)},removeHook:function(e,t){var r=this._getNonPropHooksByName(e);r&&function(e,t){for(var r,n=0;(r=e.indexOf(t))>-1;)e.splice(r,1),n++}(r,t)},hasHook:function(e){return this._getNonPropHooksByName(e)||this[e]},executeHook:function(e,t){var r=this,n=this._getNonPropHooksByName(e);return n=n?n.slice():[],this[e]&&S(this[e])&&n.push((function(t){for(var n=arguments.length,o=new Array(n>1?n-1:0),a=1;a0&&e(d,{attrs:{name:t.$props.foldingTransitionName}},[!o.$folded&&n(o.children,o,u)])])}))])}(this.rootNode.children,this.rootNode,[]),this.blockFooter&&this.blockFooter()])},mixins:[function(e){e=S(e)?e():Object.assign({},e);var t={},r=function(r){var n=e[r];n.$localName||(n.$localName="localProps_".concat(r)),n.$localSetter||(n.$localSetter=function(e){return e});var o={};t[r]=o,Object.keys(e[r]).forEach((function(e){"$"!==e[0]&&(o[e]=n[e])}))};for(var n in e)r(n);for(var o={props:t,computed:{},watch:{},data:function(){for(var t={localValueOfUpdatableProps:{}},r=0,n=Object.keys(e);r2&&void 0!==arguments[2]?arguments[2]:{};(r=he({foldOthers:!1},r)).foldOthers&&this.foldAll(),e.$folded&&(this.$set(e,"$folded",!1),this.$emit("nodeFoldedChanged",e),this.$emit("node-folded-changed",e))},toggleFold:function(e,t,r){e.$folded?this.unfold(e,t,r):this.fold(e,t,r)},foldAll:function(){var e=this;this.walkTreeData((function(t){e.fold(t)}))},unfoldAll:function(){var e=this;this.walkTreeData((function(t){e.unfold(t,{unfoldParent:!1})}))}},mounted:function(){this.foldAllAfterMounted&&this.foldAll()}};function ge(e,t){var r;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return ve(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ve(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,i=!0,l=!1;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return i=e.done,e},e:function(e){l=!0,a=e},f:function(){try{i||null==r.return||r.return()}finally{if(l)throw a}}}}function ve(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r0&&oe(e.children,(function(t){r.$set(t,"$checked",e.$checked)}))},check:function(e,t){this.$set(e,"$checked",!0),this.afterCheckChanged(e,t)},uncheck:function(e,t){this.$set(e,"$checked",!1),this.afterCheckChanged(e,t)},toggleCheck:function(e,t){this.$set(e,"$checked",!e.$checked),this.afterCheckChanged(e,t)}}};function me(e,t,r,n,o,a,i){try{var l=e[a](i),c=l.value}catch(e){return void r(e)}l.done?t(c):Promise.resolve(c).then(n,o)}var be=function(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var a=e.apply(t,r);function i(e){me(a,n,o,i,l,"next",e)}function l(e){me(a,n,o,i,l,"throw",e)}i(void 0)}))}},xe={start:["mousedown","touchstart"],move:["mousemove","touchmove"],end:["mouseup","touchend"]},Se={isTouch:function(e){return e.type&&e.type.startsWith("touch")},_getStore:function(e){return e._wrapperStore||(e._wrapperStore=[]),e._wrapperStore},on:function(e,t,r,n){var o,a,i=we(n),c=i.args,s=i.mouseArgs,u=i.touchArgs,d=this._getStore(e),f=this,h=function(e){var n;if(f.isTouch(e))n={x:e.changedTouches[0].pageX,y:e.changedTouches[0].pageY,pageX:e.changedTouches[0].pageX,pageY:e.changedTouches[0].pageY,clientX:e.changedTouches[0].clientX,clientY:e.changedTouches[0].clientY,screenX:e.changedTouches[0].screenX,screenY:e.changedTouches[0].screenY};else if(n={x:e.pageX,y:e.pageY,pageX:e.pageX,pageY:e.pageY,clientX:e.clientX,clientY:e.clientY,screenX:e.screenX,screenY:e.screenY},"start"===t&&1!==e.which)return;return r.call(this,e,n)};d.push({handler:r,wrapper:h}),(o=X).call.apply(o,[null,e,xe[t][0],h].concat([].concat(l(c),l(s)))),(a=X).call.apply(a,[null,e,xe[t][1],h].concat([].concat(l(c),l(u))))},off:function(e,t,r,n){for(var o=we(n),a=o.args,i=o.mouseArgs,c=this._getStore(e),s=c.length-1;s>=0;s--){var u,d,f=c[s],h=f.handler,p=f.wrapper;if(r===h)(u=R).call.apply(u,[null,e,xe[t][0],p].concat([].concat(l(a),l(i)))),(d=R).call.apply(d,[null,e,xe[t][1],p].concat([].concat(l(a),l(i)))),c.splice(s,1)}}}; -/*! - * drag-event-service v1.1.7 - * (c) phphe (https://github.com/phphe) - * Homepage: undefined - * Released under the MIT License. - */function we(e){return e||(e={}),{args:e.args||[],mouseArgs:e.mouseArgs||[],touchArgs:e.touchArgs||[]}} -/*! - * draggable-helper v5.0.6 - * (c) phphe (https://github.com/phphe) - * Homepage: undefined - * Released under the MIT License. - */function Ee(e){if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(e=function(e,t){if(!e)return;if("string"==typeof e)return ke(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ke(e,t)}(e))){var t=0,r=function(){};return{s:r,n:function(){return t>=e.length?{done:!0}:{done:!1,value:e[t++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,o,a=!0,i=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return a=e.done,e},e:function(e){i=!0,o=e},f:function(){try{a||null==n.return||n.return()}finally{if(i)throw o}}}}function ke(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r1&&void 0!==arguments[1]?arguments[1]:{};P(r,Oe);var n=function(n,i){Se.isTouch(n)?r.ontouchstart&&r.ontouchstart(n):r.onmousedown&&r.onmousedown(n);var l=n.target;if(!r.ingoreTags.includes(l.tagName)&&(!Y(l,r.undraggableClassName)&&!F(l,(function(t){return!!Y(t,r.undraggableClassName)||(t===e?"break":void 0)})))){(t=JSON.parse(JSON.stringify(Be))).startEvent=n,t.listenerElement=e,t.directTriggerElement=l,t.initialMouse=Object.assign({},i);var c=!1;if(r.getTriggerElement){var s=r.getTriggerElement(t.directTriggerElement,t);if(!s)return;t.triggerElement=s}else if(r.triggerClassName){var u,d,f=Ee(T(r.triggerClassName));try{var h=function(){var r=d.value;if(u=F(t.directTriggerElement,(function(t){return!!Y(t,r)||(t===e?"break":void 0)}),{withSelf:!0}))return"break"};for(f.s();!(d=f.n()).done;){if("break"===h())break}}catch(e){f.e(e)}finally{f.f()}if(!u)return;t.triggerElement=u}else c=!0;t.movedOrClonedElement=r.getMovedOrClonedElement?r.getMovedOrClonedElement(t.directTriggerElement,t,r):e,t.movedOrClonedElement&&(c&&(t.triggerElement=t.movedOrClonedElement),r.triggerBySelf&&t.triggerElement!==t.directTriggerElement||(Se.isTouch(n)||r.preventTextSelection&&n.preventDefault(),Se.on(document,"move",o,{touchArgs:[{passive:!1}]}),Se.on(window,"end",a)))}};Se.on(e,"start",n,{touchArgs:[{passive:!0}]});var o=function(e,n){Se.isTouch(e)?r.ontouchmove&&r.ontouchmove(e):r.onmousemove&&r.onmousemove(e);var o=t.movedOrClonedElement,a=t.move={x:n.clientX-t.initialMouse.clientX,y:n.clientY-t.initialMouse.clientY};if(t.moveEvent=e,t.mouse=n,(Se.isTouch(e)||r.preventTextSelection)&&e.preventDefault(),0===t.movedCount){if(r.minDisplacement){var i=Math.pow(a.x,2),l=Math.pow(a.y,2);if(Math.pow(i+l,.5)=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,i=!0,l=!1;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return i=e.done,e},e:function(e){l=!0,a=e},f:function(){try{i||null==r.return||r.return()}finally{if(l)throw a}}}}function je(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,i=!0,l=!1;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return i=e.done,e},e:function(e){l=!0,a=e},f:function(){try{i||null==r.return||r.return()}finally{if(l)throw a}}}}function Ie(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);rv.clientWidth){var y=k(v);u.x<=y.left+r?E(v,"left")>10&&w(v,"x")&&(n=v,i="left"):u.x>=y.left+v.clientWidth-r&&E(v,"right")>10&&w(v,"x")&&(n=v,i="right")}if(n)break;a=v}}}catch(e){g.e(e)}finally{g.f()}if(a=null,c=null,t.edgeScrollSpecifiedContainerY)(p="function"==typeof t.edgeScrollSpecifiedContainerY?t.edgeScrollSpecifiedContainerY(e,t):t.edgeScrollSpecifiedContainerY)&&(c=[p]);c||(c=s||V(u.x,u.y));var m,b=Ee(c);try{for(b.s();!(m=b.n()).done;){var x=m.value;if(!a||M(a,x)){if(!o&&x.scrollHeight>x.clientHeight){var S=k(x);u.y<=S.top+r?E(x,"up")>10&&w(x,"y")&&(o=x,l="up"):u.y>=S.top+x.clientHeight-r&&E(x,"down")>10&&w(x,"y")&&(o=x,l="down")}if(o)break;a=x}}}catch(e){b.e(e)}finally{b.f()}n&&(Ce=q("left"===i?{x:0,element:n,duration:E(n,"left")/t.edgeScrollSpeed}:{x:n.scrollWidth-n.clientWidth,element:n,duration:E(n,"right")/t.edgeScrollSpeed})),o&&(Pe=q("up"===l?{y:0,element:o,duration:E(o,"up")/t.edgeScrollSpeed}:{y:o.scrollHeight-o.clientHeight,element:o,duration:E(o,"down")/t.edgeScrollSpeed}))}function w(e,t){var r=getComputedStyle(e),n="overflow-".concat(t);return e===(document.scrollingElement||document.documentElement)?"visible"===r[n]||"auto"===r[n]||"scroll"===r[n]:"auto"===r[n]||"scroll"===r[n]}function E(e,t){return"up"===t?e.scrollTop:"down"===t?e.scrollHeight-e.scrollTop-e.clientHeight:"left"===t?e.scrollLeft:"right"===t?e.scrollWidth-e.scrollLeft-e.clientWidth:void 0}function k(e){var t=L(e);return e===(document.scrollingElement||document.documentElement)&&(t.top=0,t.left=0),t}},Te.afterDrop=function(e,t){t.edgeScroll&&De()};var He={},Ye=ue({},void 0,{props:{triggerClass:{type:[String,Array],default:"tree-node"},triggerBySelf:{type:Boolean},draggable:{type:[Boolean,Function],default:!0},droppable:{type:[Boolean,Function],default:!0},eachDraggable:{type:[Function]},eachDroppable:{type:[Function]},ondragstart:{type:Function},ondragend:{type:Function},unfoldWhenDragover:{type:Boolean,default:!0},unfoldWhenDragoverDelay:{type:Number,default:30},draggingNodePositionMode:{type:String,default:"top_left_corner"},edgeScroll:{type:Boolean},edgeScrollTriggerMargin:{type:Number,default:50},edgeScrollSpeed:{type:Number,default:.35},edgeScrollTriggerMode:{type:String,default:"top_left_corner"},edgeScrollSpecifiedContainerX:{},edgeScrollSpecifiedContainerY:{},preventTextSelection:{type:Boolean,default:!0}},data:function(){return{treesStore:He}},methods:{_Draggable_unfoldTargetNodeByEl:function(e,t){var r=t.targetTree,n=r.getPathByBranchEl(e),o=r.getNodeByPath(n);return r.unfold&&r.unfold(o,n),new Promise((function(e,t){r.$nextTick((function(){e()}))}))},isNodeDraggable:function(e,t){var r=this.treesStore.store,n=this.getAllNodesByPath(t);n.unshift(this.rootNode);var o,a=Fe(C(n,{reverse:!0}));try{for(a.s();!(o=a.n()).done;){var i=o.value,l=i.value,c=i.index,s=t.slice(0,c+1),u=D(void 0!==l.$draggable?l.$draggable:this.eachDraggable,[s,this,r]);if(void 0!==u)return u}}catch(e){a.e(e)}finally{a.f()}return!0},isNodeDroppable:function(e,t){var r,n,o=this.treesStore.store,a=this.getAllNodesByPath(t);a.unshift(this.rootNode);var i,l=Fe(C(a,{reverse:!0}));try{for(l.s();!(i=l.n()).done;){var c=i.value,s=c.value,u=c.index,d=t.slice(0,u+1),f=D(void 0!==s.$droppable?s.$droppable:this.eachDroppable,[d,this,o]);if(void 0!==f){r=f,n=!0;break}}}catch(e){l.e(e)}finally{l.f()}return n||(r=!0),this._internal_hook_isNodeDroppable?this._internal_hook_isNodeDroppable({droppableFinal:r,node:e,path:t,store:o}):r},getPathByBranchEl:function(e){this.treesStore.store;var t,r=function(e){var t=e.getAttribute("data-tree-node-path");if(t)return t.split(",").map((function(e){return parseInt(e)}))},n=r(e);if(n)return n;F(e,(function(e){return Y(e,"tree-root")?(t=[],!0):Y(e,"tree-branch")?(t=r(e),!0):void 0}));var o,a=0,i=Fe(C(e.parentElement.children));try{for(i.s();!(o=i.n()).done;){var c=o.value,s=c.value;c.index;if(Y(s,"tree-branch")||Y(s,"tree-placeholder")){if(s===e)break;a++}}}catch(e){i.e(e)}finally{i.f()}return[].concat(l(t),[a])}},mounted:function(){var e=this,t=this._draggableOptions={indent:this.indent,triggerClass:this.triggerClass,triggerBySelf:this.triggerBySelf,unfoldWhenDragover:this.unfoldWhenDragover,unfoldWhenDragoverDelay:this.unfoldWhenDragoverDelay,draggingNodePositionMode:this.draggingNodePositionMode,cloneWhenDrag:this.cloneWhenDrag,edgeScroll:this.edgeScroll,edgeScrollTriggerMargin:this.edgeScrollTriggerMargin,edgeScrollSpeed:this.edgeScrollSpeed,edgeScrollTriggerMode:this.edgeScrollTriggerMode,edgeScrollSpecifiedContainerX:this.edgeScrollSpecifiedContainerX,edgeScrollSpecifiedContainerY:this.edgeScrollSpecifiedContainerY,rtl:this.rtl,preventTextSelection:this.preventTextSelection,treeClass:"he-tree",rootClass:"tree-root",childrenClass:"tree-children",branchClass:"tree-branch",nodeClass:"tree-node",nodeBackClass:"tree-node-back",placeholderClass:"tree-placeholder",placeholderNodeBackClass:"tree-placeholder-node-back",placeholderNodeClass:"tree-placeholder-node",draggingClass:"dragging",placeholderId:"he_tree_drag_placeholder",ifNodeFolded:function(e,t){return t.targetTree.getNodeByBranchEl(e).$folded},isTargetTreeRootDroppable:function(e){var t=D(e.targetTree.rootNode.$droppable,[e.targetTree,e]);return void 0===t||t},unfoldTargetNodeByEl:function(){return e._Draggable_unfoldTargetNodeByEl.apply(e,arguments)},isNodeParentDroppable:function(t,r){var n=e.getTreeVmByTreeEl(r),o=N(n.getPathByBranchEl(t),1),a=n.getNodeByPath(o);return n.isNodeDroppable(a,o)},isNodeDroppable:function(t,r){var n=e.getTreeVmByTreeEl(r),o=n.getPathByBranchEl(t),a=n.getNodeByPath(o);return n.isNodeDroppable(a,o)},_findClosestDroppablePosition:function(t,r){var n,o=e.getTreeVmByTreeEl(r),a=o.getPathByBranchEl(t),i=N(a,1),l=a,c=Fe(o.iteratePath(i,{reverse:!0}));try{for(c.s();!(n=c.n()).done;){var s=n.value,u=s.node,d=s.path;if(o.isNodeDroppable(u,d))return o.getBranchElByPath(l);l=d}}catch(e){c.e(e)}finally{c.f()}if(o.isNodeDroppable(e.rootNode,[]))return o.getBranchElByPath(l)},afterPlaceholderCreated:function(e){e.startTree.$emit("afterPlaceholderCreated",e),e.startTree.$emit("after-placeholder-created",e)},getPathByBranchEl:function(t){return e.getPathByBranchEl(t)},beforeFirstMove:function(t){if(e.treesStore.store=t,t.startTree=e.getTreeVmByTreeEl(t.startTreeEl),!D(t.startTree.draggable,[t.startTree,t]))return!1;var r=t.startTree,n=(t.dragBranchEl,t.startPath);return t.dragNode=r.getNodeByPath(n),e.cloneWhenDrag&&(t.dragNode=ne(t.dragNode)),!!r.isNodeDraggable(t.dragNode,n)&&((!r.hasHook("ondragstart")||!1!==r.executeHook("ondragstart",[r,t]))&&(t.startTree.$emit("before-first-move",t),t.startTree.$emit("drag",t),void e.$root.$emit("he-tree-drag",t)))},filterTargetTree:function(t,r){var n=e.getTreeVmByTreeEl(t);if(r.startTree!==n){if(!e._internal_hook_filterTargetTree)return!1;if(!1===e._internal_hook_filterTargetTree(n,r))return!1}return!!D(n.droppable,[n,r])&&(r.targetTree=n,!(!D(r.startTree===r.targetTree)&&D(e._Draggable_unfoldTargetNode,[!1,e.treeData])!==e.rootNode.children)&&void 0)},afterMove:function(e){e.startTree.$emit("after-move",e)},beforeDrop:function(t,r){var n=r.targetTree;if(n.hasHook("ondragend")&&!1===n.executeHook("ondragend",[n,r]))return!1;e.$root.$emit("he-tree-before-drop",r)},afterDrop:function(t,r){if(t.pathChanged){var n=t.startTree,o=t.targetTree,a=t.startPath,i=t.dragNode,l=t.targetPath;if(!0!==e.cloneWhenDrag){var c=N(a,1),s=n.getNodeByPath(c),u=0===c.length?n.treeData:s.children,d=k(a);u.splice(d,1)}var f,h=N(l,1),p=o.getNodeByPath(h);0===h.length?f=o.treeData:(p.children||e.$set(p,"children",[]),f=p.children);var g=k(l);return f.splice(g,0,i),n.$emit("input",n.treeData),n.$emit("change",t),o.$emit("drop",t),e.$root.$emit("he-tree-drop",t),o!==n&&(o.$emit("input",o.treeData),o.$emit("change",t)),new Promise((function(e,t){o.$nextTick((function(){e()}))}))}}},r=this._makeTreeDraggable_obj=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=Ae(Ae({},t),{},{treeEl:e});var r,n=Ne(e,{triggerClassName:t.triggerClass,triggerBySelf:t.triggerBySelf,draggingClassName:t.draggingClass,clone:t.cloneWhenDrag,edgeScroll:t.edgeScroll,edgeScrollTriggerMargin:t.edgeScrollTriggerMargin,edgeScrollSpeed:t.edgeScrollSpeed,edgeScrollTriggerMode:t.edgeScrollTriggerMode,edgeScrollSpecifiedContainerX:t.edgeScrollSpecifiedContainerX,edgeScrollSpecifiedContainerY:t.edgeScrollSpecifiedContainerY,rtl:t.rtl,preventTextSelection:t.preventTextSelection,updateMovedElementStyleManually:!0,getMovedOrClonedElement:function(e,r){return F(r.triggerElement,(function(e){return Y(e,t.branchClass)}),{withSelf:!0})},beforeFirstMove:function(r,n){if(r.startTreeEl=e,r.dragBranchEl=r.movedElement,r.startPath=t.getPathByBranchEl(r.movedOrClonedElement),t.beforeFirstMove&&!1===t.beforeFirstMove(r,n))return!1},beforeMove:function(e,r){var n=function(){var r=t.getPathByBranchEl(e.placeholder);e.placeholder.querySelector(".".concat(t.nodeBackClass)).style[t.rtl?"paddingRight":"paddingLeft"]=(r.length-1)*t.indent+"px",0===e.tempChildren.children.length&&j(e.tempChildren)};if(0===e.movedCount){var o=_('\n
\n
\n
\n
\n
\n
\n '));K(o,e.movedOrClonedElement),e.placeholder=o,t.afterPlaceholderCreated(e);var a=document.createElement("DIV");return W(a,t.childrenClass),e.tempChildren=a,n(),void e.updateMovedElementStyle()}e.updateMovedElementStyle(),e.oneMoveStore={};var l,c,s,u=e.movedElement,d=u.querySelector(".".concat(t.nodeClass)),f=$(d),h=A(d);if("mouse"===t.draggingNodePositionMode){var p=e.moveEvent;f={x:p.pageX,y:p.pageY},h={x:p.clientX,y:p.clientY}}else t.rtl&&(f.x+=d.offsetWidth,h.x+=d.offsetWidth);var v,y=Me(V(h.x,h.y));try{for(y.s();!(v=y.n()).done;){var m=v.value;if(s||(s=m),Y(m,t.treeClass)){c=m;break}}}catch(e){y.e(e)}finally{y.f()}if(s===c||M(s,c)||(c=null),(l=c)&&!1!==t.filterTargetTree(l,e,r)){e.targetTreeEl=l;var b={tree:function(){return l},root:function(){return b.tree.querySelector(".".concat(t.childrenClass))},closestNode:function(){var e=[];if(function r(n){if(n!==b.tree){var o=n.querySelector(".".concat(t.nodeClass));o&&!Le(o)&&e.push(o)}var a=n.querySelector(".".concat(t.childrenClass));if(a)for(var i=0;i=f.x)break}else if($(a).x<=f.x)break;for(var i=void 0,l=n.nextSibling;l;){if(l!==u&&l!==e.placeholder&&Y(l,t.branchClass)&&!Le(l)){i=!0;break}l=l.nextSibling}if(i)break;var c=F(n,(function(e){return Y(e,t.branchClass)}));if(!c)break;n=c}return n}}},x={"no closest":function(){return!b.closestNode},"closest is top":function(){return b.closestBranch===U(b.root.children,(function(e){return e!==u&&!Le(e)}))},"closest is top excluding placeholder":function(){return b.closestBranch===U(b.root.children,(function(t){return t!==u&&t!==e.placeholder&&!Le(t)}))},"on closest middle":function(){return f.yb.closestNodeOffset.x+t.indent},"at closest left":function(){return f.xb.closestNodeOffset.x+b.closestNode.offsetWidth}}),Object.keys(x).forEach((function(e){var t=x[e];x[e]=function(){return Boolean(t.call(this))}})),te(b,b),te(x,x),e.oneMoveStore.info=b,e.oneMoveStore.conditions=x;var S=function(t){for(var r=arguments.length,o=new Array(r>1?r-1:0),a=1;a0&&void 0!==r[0]?r[0]:b.closestBranch,!t.isNodeParentDroppable(o,e.targetTreeEl)){n.next=5;break}K(e.placeholder,o),n.next=11;break;case 5:return n.next=7,E(i(o));case 7:if(a=n.sent,l=!e.oneMoveStore.actionRecords||1===e.oneMoveStore.actionRecords.length,a||!l){n.next=11;break}return n.abrupt("return",k(o));case 11:case"end":return n.stop()}}),n)})))()},prepend:function(){return be(g.mark((function r(){return g.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(b.closestBranch!==e.placeholder){r.next=2;break}return r.abrupt("return");case 2:if(!t.ifNodeFolded(b.closestBranch,e)||t.unfoldWhenDragover){r.next=6;break}return r.abrupt("return",S("insert after",b.closestBranch));case 6:if(!t.isNodeDroppable(b.closestBranch,e.targetTreeEl)){r.next=11;break}return r.next=9,N(b.closestBranch);case 9:r.next=12;break;case 11:return r.abrupt("return",E(b.closestBranch));case 12:case"end":return r.stop()}}),r)})))()},"after above":function(){return be(g.mark((function r(){return g.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!t.isNodeParentDroppable(b.aboveBranch,e.targetTreeEl)){r.next=4;break}K(e.placeholder,b.aboveBranch),r.next=5;break;case 4:return r.abrupt("return",E(i(b.aboveBranch)));case 5:case"end":return r.stop()}}),r)})))()},"append to prev":function(){return be(g.mark((function r(){var n;return g.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(b.closestPrev!==e.placeholder){r.next=2;break}return r.abrupt("return");case 2:if(!t.ifNodeFolded(b.closestPrev,e)){r.next=6;break}return r.abrupt("return",S("insert after",b.closestPrev));case 6:if(!t.isNodeDroppable(b.closestPrev,e.targetTreeEl)){r.next=13;break}return r.next=9,T(b.closestPrev);case 9:n=r.sent,J(e.placeholder,n),r.next=14;break;case 13:return r.abrupt("return",E(b.closestPrev));case 14:case"end":return r.stop()}}),r)})))()}},E=function(){var r=be(g.mark((function r(n){var o;return g.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!n){r.next=5;break}if(!(o=t._findClosestDroppablePosition(n,e.targetTreeEl))){r.next=5;break}return K(e.placeholder,o),r.abrupt("return",!0);case 5:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}(),k=function(){var r=be(g.mark((function r(n){return g.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(t.ifNodeFolded(n,e)||!t.isNodeDroppable(n,e.targetTreeEl)){r.next=3;break}return r.next=3,N(n);case 3:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}(),T=function(){var r=be(g.mark((function r(n){var o;return g.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,t.unfoldTargetNodeByEl(n,e);case 2:return(o=n.querySelector(".".concat(t.childrenClass)))||J(o=e.tempChildren,n),r.abrupt("return",o);case 5:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}(),N=function(){var r=be(g.mark((function r(n){var o,a;return g.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(o=function(){var t=be(g.mark((function t(){var r;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,T(n);case 2:r=t.sent,Q(e.placeholder,r);case 4:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),!t.ifNodeFolded(n,e)){r.next=6;break}a=e.oneMoveStore,setTimeout((function(){a===e.oneMoveStore&&o()}),t.unfoldWhenDragoverDelay),r.next=8;break;case 6:return r.next=8,o();case 8:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}();_e({options:t,event:e.moveEvent,store:e,opt:r,info:b,conditions:x,actions:w,doAction:S})}},afterMove:function(e,r){t.afterMove&&t.afterMove(e,r)},beforeDrop:(r=be(g.mark((function e(r,n){var o,a,i,l,c,s,u,d;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return d=function(){var e=r.startTree,n=r.targetTree,o=r.startPath,a=r.placeholderPath.slice(0);if(!0!==t.cloneWhenDrag&&e===n&&o.length<=a.length){var i=o.slice(0,o.length-1),l=a.slice(0,i.length);if(i.toString()===l.toString()){var c=i.length;o[c] - + - he-tree + <%= htmlWebpackPlugin.options.title %>
-
diff --git a/scripts/build.js b/scripts/build.js index 9cf7121..fac5601 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -2,57 +2,67 @@ Object.defineProperty(exports, "__esModule", { value: true }); const rogo_1 = require("rogo"); const path = require("path"); -const babel = require('rollup-plugin-babel'); +const babel = require("rollup-plugin-babel"); const node = require("@rollup/plugin-node-resolve"); const cjs = require("@rollup/plugin-commonjs"); const json = require("@rollup/plugin-json"); const rollup_plugin_terser_1 = require("rollup-plugin-terser"); // to minify bundle +const typescript = require("rollup-plugin-typescript2"); const vue = require("rollup-plugin-vue"); -const postcss = require('rollup-plugin-postcss'); +const postcss = require("rollup-plugin-postcss"); const pkg = require("../package.json"); +const external = ["tslib"]; // quick config -const input = 'src/index.js'; -const outDir = 'dist'; +const input = "src/index.ts"; +const outDir = "dist"; const outputName = pkg.name; // the built file name is outDir/outputName.format.js const moduleName = rogo_1.camelize(pkg.name); // for umd, amd const extractCssPath = path.resolve(outDir, `${outputName}.css`); const getBabelConfig = () => ({ // .babelrc presets: [ - ['@vue/cli-plugin-babel/preset', { + [ + "@vue/cli-plugin-babel/preset", + { useBuiltIns: false, polyfills: [], - targets: 'defaults', - }], + targets: { browsers: "defaults" }, + }, + ], ], plugins: [ - '@babel/plugin-transform-runtime', - ['@babel/plugin-proposal-optional-chaining', { 'loose': false }], + "@babel/plugin-transform-runtime", + ["@babel/plugin-proposal-optional-chaining", { loose: false }], ], // for rollup babel plugin runtimeHelpers: true, exclude: [/@babel\/runtime/, /@babel\\runtime/, /regenerator-runtime/], - extensions: ['.js', '.jsx', '.es6', '.es', '.mjs', '.vue', '.ts', '.tsx'], + extensions: [".js", ".jsx", ".es6", ".es", ".mjs", ".vue", ".ts", ".tsx"], babelrc: false, }); const esmBabelConfig = getBabelConfig(); const cjsBabelConfig = getBabelConfig(); -cjsBabelConfig.plugins.push(['module-extension', { mjs: 'js' }]); // replace .mjs to .js +cjsBabelConfig.plugins.push(["module-extension", { mjs: "js" }]); // replace .mjs to .js const umdBabelConfig = getBabelConfig(); exports.default = [ // esm { input, - external: (source) => rogo_1.belongsTo(source, Object.keys(pkg.dependencies || {})) || rogo_1.belongsTo(source, Object.keys(pkg.peerDependencies || {})), + external: (source) => rogo_1.belongsTo(source, Object.keys(pkg.dependencies || {})) || + rogo_1.belongsTo(source, Object.keys(pkg.peerDependencies || {})) || + rogo_1.belongsTo(source, external), plugins: [ - vue({ css: false }), + vue(), postcss({ extract: extractCssPath }), + typescript(), babel(esmBabelConfig), - node(), cjs(), json(), + node(), + cjs(), + json(), ], output: { - file: path.resolve(outDir, `${outputName}.esm.js`), - format: 'esm', + dir: `${outDir}/esm`, + format: "esm", banner: getBanner(pkg), sourcemap: false, }, @@ -60,16 +70,21 @@ exports.default = [ // cjs { input, - external: (source) => rogo_1.belongsTo(source, Object.keys(pkg.dependencies || {})) || rogo_1.belongsTo(source, Object.keys(pkg.peerDependencies || {})), + external: (source) => rogo_1.belongsTo(source, Object.keys(pkg.dependencies || {})) || + rogo_1.belongsTo(source, Object.keys(pkg.peerDependencies || {})) || + rogo_1.belongsTo(source, external), plugins: [ - vue({ css: false }), + vue(), postcss({ extract: extractCssPath }), + typescript(), babel(cjsBabelConfig), - node(), cjs(), json(), + node(), + cjs(), + json(), ], output: { - file: path.resolve(outDir, `${outputName}.cjs.js`), - format: 'cjs', + dir: `${outDir}/cjs`, + format: "cjs", banner: getBanner(pkg), sourcemap: false, }, @@ -79,14 +94,17 @@ exports.default = [ input, external: (source) => rogo_1.belongsTo(source, Object.keys(pkg.peerDependencies || {})), plugins: [ - vue({ css: false }), + vue(), postcss({ extract: extractCssPath }), + typescript(), babel(umdBabelConfig), - node(), cjs(), json(), + node(), + cjs(), + json(), ], output: { - file: path.resolve(outDir, `${outputName}.js`), - format: 'umd', + dir: `${outDir}/umd`, + format: "umd", banner: getBanner(pkg), sourcemap: false, name: moduleName, @@ -97,22 +115,25 @@ exports.default = [ input, external: (source) => rogo_1.belongsTo(source, Object.keys(pkg.peerDependencies || {})), plugins: [ - vue({ css: false }), + vue(), postcss({ extract: extractCssPath }), + typescript(), babel(umdBabelConfig), - node(), cjs(), json(), + node(), + cjs(), + json(), rollup_plugin_terser_1.terser(), ], output: { - file: path.resolve(outDir, `${outputName}.min.js`), - format: 'umd', + dir: `${outDir}/umd-min`, + format: "umd", banner: getBanner(pkg), sourcemap: false, name: moduleName, }, }, ]; -if (process.argv.includes('--report')) { +if (process.argv.includes("--report")) { rogo_1.report(outDir); } function getBanner(pkg) { diff --git a/scripts/build.ts b/scripts/build.ts index c673d99..cb04cea 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -1,63 +1,74 @@ -import {belongsTo, report, camelize} from "rogo"; +import { belongsTo, report, camelize } from "rogo"; import * as rollup from "rollup"; import * as path from "path"; -const babel = require('rollup-plugin-babel'); +const babel = require("rollup-plugin-babel"); const node = require("@rollup/plugin-node-resolve"); const cjs = require("@rollup/plugin-commonjs"); const json = require("@rollup/plugin-json"); import { terser } from "rollup-plugin-terser"; // to minify bundle +const typescript = require("rollup-plugin-typescript2"); const vue = require("rollup-plugin-vue"); -const postcss = require('rollup-plugin-postcss') -const pkg = require("../package.json") +const postcss = require("rollup-plugin-postcss"); +const pkg = require("../package.json"); +const external = ["tslib"]; // quick config -const input = 'src/index.js' -const outDir = 'dist' -const outputName = pkg.name // the built file name is outDir/outputName.format.js -const moduleName = camelize(pkg.name) // for umd, amd -const extractCssPath = path.resolve(outDir, `${outputName}.css`) +const input = "src/index.ts"; +const outDir = "dist"; +const outputName = pkg.name; // the built file name is outDir/outputName.format.js +const moduleName = camelize(pkg.name); // for umd, amd +const extractCssPath = path.resolve(outDir, `${outputName}.css`); const getBabelConfig = () => ({ // .babelrc presets: [ - ['@vue/cli-plugin-babel/preset', { - useBuiltIns: false, - polyfills: [], - targets: 'defaults', // default browsers, coverage 90% - }], + [ + "@vue/cli-plugin-babel/preset", + { + useBuiltIns: false, + polyfills: [], + targets: { browsers: "defaults" }, // default browsers, coverage 90% + }, + ], ], plugins: [ - '@babel/plugin-transform-runtime', - ['@babel/plugin-proposal-optional-chaining', { 'loose': false }], + "@babel/plugin-transform-runtime", + ["@babel/plugin-proposal-optional-chaining", { loose: false }], ], // for rollup babel plugin runtimeHelpers: true, exclude: [/@babel\/runtime/, /@babel\\runtime/, /regenerator-runtime/], - extensions: ['.js', '.jsx', '.es6', '.es', '.mjs', '.vue', '.ts', '.tsx'], + extensions: [".js", ".jsx", ".es6", ".es", ".mjs", ".vue", ".ts", ".tsx"], babelrc: false, -}) +}); -const esmBabelConfig = getBabelConfig() +const esmBabelConfig = getBabelConfig(); -const cjsBabelConfig = getBabelConfig() -cjsBabelConfig.plugins.push(['module-extension', {mjs: 'js'}]) // replace .mjs to .js +const cjsBabelConfig = getBabelConfig(); +cjsBabelConfig.plugins.push(["module-extension", { mjs: "js" }]); // replace .mjs to .js -const umdBabelConfig = getBabelConfig() +const umdBabelConfig = getBabelConfig(); export default [ // esm { input, - external: (source) => belongsTo(source, Object.keys(pkg.dependencies||{})) || belongsTo(source, Object.keys(pkg.peerDependencies||{})), + external: (source) => + belongsTo(source, Object.keys(pkg.dependencies || {})) || + belongsTo(source, Object.keys(pkg.peerDependencies || {})) || + belongsTo(source, external), plugins: [ - vue({css: false}), - postcss({extract: extractCssPath}), + vue(), + postcss({ extract: extractCssPath }), + typescript(), // node must be in front of typescript. babel must behind typescript. babel(esmBabelConfig), - node(), cjs(), json(), + node(), + cjs(), + json(), ], output: { - file: path.resolve(outDir, `${outputName}.esm.js`), - format: 'esm', + dir: `${outDir}/esm`, + format: "esm", banner: getBanner(pkg), sourcemap: false, }, @@ -65,16 +76,22 @@ export default [ // cjs { input, - external: (source) => belongsTo(source, Object.keys(pkg.dependencies||{})) || belongsTo(source, Object.keys(pkg.peerDependencies||{})), + external: (source) => + belongsTo(source, Object.keys(pkg.dependencies || {})) || + belongsTo(source, Object.keys(pkg.peerDependencies || {})) || + belongsTo(source, external), plugins: [ - vue({css: false}), - postcss({extract: extractCssPath}), + vue(), + postcss({ extract: extractCssPath }), + typescript(), // node must be in front of typescript. babel must behind typescript. babel(cjsBabelConfig), - node(), cjs(), json(), + node(), + cjs(), + json(), ], output: { - file: path.resolve(outDir, `${outputName}.cjs.js`), - format: 'cjs', + dir: `${outDir}/cjs`, + format: "cjs", banner: getBanner(pkg), sourcemap: false, }, @@ -82,16 +99,20 @@ export default [ // umd { input, - external: (source) => belongsTo(source, Object.keys(pkg.peerDependencies||{})), + external: (source) => + belongsTo(source, Object.keys(pkg.peerDependencies || {})), plugins: [ - vue({css: false}), - postcss({extract: extractCssPath}), + vue(), + postcss({ extract: extractCssPath }), + typescript(), // node must be in front of typescript. babel must behind typescript. babel(umdBabelConfig), - node(), cjs(), json(), + node(), + cjs(), + json(), ], output: { - file: path.resolve(outDir, `${outputName}.js`), - format: 'umd', + dir: `${outDir}/umd`, + format: "umd", banner: getBanner(pkg), sourcemap: false, name: moduleName, @@ -100,26 +121,30 @@ export default [ // umd min { input, - external: (source) => belongsTo(source, Object.keys(pkg.peerDependencies||{})), + external: (source) => + belongsTo(source, Object.keys(pkg.peerDependencies || {})), plugins: [ - vue({css: false}), - postcss({extract: extractCssPath}), + vue(), + postcss({ extract: extractCssPath }), + typescript(), // node must be in front of typescript. babel must behind typescript. babel(umdBabelConfig), - node(), cjs(), json(), + node(), + cjs(), + json(), terser(), // to minify bundle ], output: { - file: path.resolve(outDir, `${outputName}.min.js`), - format: 'umd', + dir: `${outDir}/umd-min`, + format: "umd", banner: getBanner(pkg), sourcemap: false, name: moduleName, }, }, -] +]; -if (process.argv.includes('--report')) { - report(outDir) +if (process.argv.includes("--report")) { + report(outDir); } function getBanner(pkg) { @@ -129,5 +154,5 @@ function getBanner(pkg) { * (c) ${pkg.author} * Homepage: ${pkg.homepage} * Released under the ${pkg.license} License. - */`.trim() -} \ No newline at end of file + */`.trim(); +} diff --git a/src/App.vue b/src/App.vue index 6d5b2e9..3cbf188 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,77 +1,263 @@ - - - - - - + + + + + diff --git a/src/BaseTree.vue b/src/BaseTree.vue new file mode 100644 index 0000000..e38c2a1 --- /dev/null +++ b/src/BaseTree.vue @@ -0,0 +1,514 @@ + + + + + diff --git a/src/assets/simple-grid.scss b/src/assets/simple-grid.scss new file mode 100644 index 0000000..0dad67f --- /dev/null +++ b/src/assets/simple-grid.scss @@ -0,0 +1,243 @@ +// SIMPLE GRID - SASS/SCSS + +// @import url( +// https://fonts.googleapis.com/css?family=Lato:400, +// 300, +// 300italic, +// 400italic, +// 700, +// 700italic +// ); + +// fonts +$font-family: "Lato", Helvetica, sans-serif; +$font-weight-light: 300; +$font-weight-regular: 400; +$font-weight-heavy: 700; +$font-height: 1.5; + +// colors +$dark-grey: #333447; +$dark-gray: #333447; // for the Americans + +// universal + +html, +body { + height: 100%; + width: 100%; + margin: 0; + padding: 0; + left: 0; + top: 0; + font-size: 100%; +} + +* { + font-family: $font-family; + color: $dark-grey; + line-height: $font-height; +} + +// typography + +h1 { + font-size: 2.5rem; +} + +h2 { + font-size: 2rem; +} + +h3 { + font-size: 1.375rem; +} + +h4 { + font-size: 1.125rem; +} + +h5 { + font-size: 1rem; +} + +h6 { + font-size: 0.875rem; +} + +p { + font-size: 1.125rem; + font-weight: 200; + line-height: 1.8; +} + +.font-light { + font-weight: $font-weight-light; +} + +.font-regular { + font-weight: $font-weight-regular; +} + +.font-heavy { + font-weight: $font-weight-heavy; +} + +// utility + +.left { + text-align: left; +} + +.right { + text-align: right; +} + +.center { + text-align: center; + margin-left: auto; + margin-right: auto; +} + +.justify { + text-align: justify; +} + +.hidden-sm { + display: none; +} + +// grid + +$width: 96%; +$gutter: 4%; +$breakpoint-small: 33.75em; // 540px +$breakpoint-med: 45em; // 720px +$breakpoint-large: 60em; // 960px + +.container { + width: 90%; + margin-left: auto; + margin-right: auto; + + @media only screen and (min-width: $breakpoint-small) { + width: 80%; + } + + @media only screen and (min-width: $breakpoint-large) { + width: 75%; + max-width: 60rem; + } +} + +.row { + position: relative; + width: 100%; +} + +.row [class^="col"] { + float: left; + margin: 0.5rem 2%; + min-height: 0.125rem; +} + +.row::after { + content: ""; + display: table; + clear: both; +} + +.col-1, +.col-2, +.col-3, +.col-4, +.col-5, +.col-6, +.col-7, +.col-8, +.col-9, +.col-10, +.col-11, +.col-12 { + width: $width; +} + +.col-1-sm { + width: ($width / 12) - ($gutter * 11 / 12); +} +.col-2-sm { + width: ($width / 6) - ($gutter * 10 / 12); +} +.col-3-sm { + width: ($width / 4) - ($gutter * 9 / 12); +} +.col-4-sm { + width: ($width / 3) - ($gutter * 8 / 12); +} +.col-5-sm { + width: ($width / (12 / 5)) - ($gutter * 7 / 12); +} +.col-6-sm { + width: ($width / 2) - ($gutter * 6 / 12); +} +.col-7-sm { + width: ($width / (12 / 7)) - ($gutter * 5 / 12); +} +.col-8-sm { + width: ($width / (12 / 8)) - ($gutter * 4 / 12); +} +.col-9-sm { + width: ($width / (12 / 9)) - ($gutter * 3 / 12); +} +.col-10-sm { + width: ($width / (12 / 10)) - ($gutter * 2 / 12); +} +.col-11-sm { + width: ($width / (12 / 11)) - ($gutter * 1 / 12); +} +.col-12-sm { + width: $width; +} + +@media only screen and (min-width: $breakpoint-med) { + .col-1 { + width: ($width / 12) - ($gutter * 11 / 12); + } + .col-2 { + width: ($width / 6) - ($gutter * 10 / 12); + } + .col-3 { + width: ($width / 4) - ($gutter * 9 / 12); + } + .col-4 { + width: ($width / 3) - ($gutter * 8 / 12); + } + .col-5 { + width: ($width / (12 / 5)) - ($gutter * 7 / 12); + } + .col-6 { + width: ($width / 2) - ($gutter * 6 / 12); + } + .col-7 { + width: ($width / (12 / 7)) - ($gutter * 5 / 12); + } + .col-8 { + width: ($width / (12 / 8)) - ($gutter * 4 / 12); + } + .col-9 { + width: ($width / (12 / 9)) - ($gutter * 3 / 12); + } + .col-10 { + width: ($width / (12 / 10)) - ($gutter * 2 / 12); + } + .col-11 { + width: ($width / (12 / 11)) - ($gutter * 1 / 12); + } + .col-12 { + width: $width; + } + + .hidden-sm { + display: block; + } +} diff --git a/src/components/Tree.vue b/src/components/Tree.vue deleted file mode 100644 index 8dd7732..0000000 --- a/src/components/Tree.vue +++ /dev/null @@ -1,176 +0,0 @@ - - - diff --git a/src/components/VirtualizationList.vue b/src/components/VirtualizationList.vue new file mode 100644 index 0000000..48103cb --- /dev/null +++ b/src/components/VirtualizationList.vue @@ -0,0 +1,178 @@ + + + + + diff --git a/src/draggable/Draggable.vue b/src/draggable/Draggable.vue new file mode 100644 index 0000000..8988de0 --- /dev/null +++ b/src/draggable/Draggable.vue @@ -0,0 +1,634 @@ + + + diff --git a/src/draggable/draggable.ts b/src/draggable/draggable.ts new file mode 100644 index 0000000..e623447 --- /dev/null +++ b/src/draggable/draggable.ts @@ -0,0 +1,354 @@ +/* eslint-disable prefer-const */ +import * as hp from "helper-js"; +import draggableHelper, { Options, Store } from "draggable-helper"; +import { obj, BaseNode } from "../types"; + +export interface Options2 extends Options { + treeClass: string; + nodeClass: string; + nodeOuterClass: string; + placeholderClass: string; + rtl: boolean; + draggingNodePositionMode: "top_left_corner" | "mouse"; +} + +export interface Store2 extends Store { + startTreeEl: HTMLElement; + targetTreeEl: HTMLElement; + placeholder: HTMLElement; +} + +interface Hooks { + beforeFirstMove?: (store: Store2, options: Options2) => boolean; + afterFirstMove?: (store: Store2, options: Options2) => void; + getNodeLevelByEl: (el: HTMLElement) => number; + createPlaceholder: () => HTMLElement; + setPlaceholderLevel: (placeholder: HTMLElement, level: number) => void; + filterTargetTreeEl?: (el: HTMLElement, store: Store2) => boolean; + afterTargetTreeElUpdated?: (store: Store2) => void; + insertedPlaceholderAfterCreated: (store: Store2) => void; + getTreeIndent: (treeEl: HTMLElement, store: Store2) => number; + moveEnd: (action: string, info?: obj) => void; + movePlaceholder: ( + store: Store2, + el: HTMLElement | undefined, + targetLevel: number + ) => void; + onDrop: (store: Store2, restoreStyle: () => void) => void; +} + +export default function makeTreeListDraggable( + treeEl: HTMLElement, + options: Options2, + hooks: Hooks +) { + const defaultOptions: Options = { + updateMovedElementStyleManually: true, + getMovedOrClonedElement: (directTriggerElement, store) => { + // find closest node from parents + const el = hp.findParent( + store.triggerElement, + (el) => hp.hasClass(el, options.nodeOuterClass), + { withSelf: true } + ); + return el; + }, + // @ts-ignore + beforeFirstMove(store: Store2, options: Options2) { + store.startTreeEl = treeEl; + if ( + hooks.beforeFirstMove && + hooks.beforeFirstMove(store, options) === false + ) { + return false; + } + }, + // it means onMove + // @ts-ignore + beforeMove(store: Store2) { + // first move + // 第一次移动 + if (store.movedCount === 0) { + // create placeholder + // 创建占位元素 + const placeholder = hooks.createPlaceholder(); + store.placeholder = placeholder; + store.targetTreeEl = store.startTreeEl; + hooks.afterTargetTreeElUpdated?.(store); + hooks.insertedPlaceholderAfterCreated(store); + hooks.setPlaceholderLevel( + store.placeholder, + hooks.getNodeLevelByEl(store.movedOrClonedElement) + ); + store.updateMovedElementStyle(); + hooks.afterFirstMove?.(store, options); + // skip first move + // 跳过第一次移动 + hooks.moveEnd("first_move"); + return; + } + // + store.updateMovedElementStyle(); + // + const movingEl = store.movedElement; // node + // find closest node and hovering tree + let tree; + const movingNode = movingEl; + // movingNodeOf and movingNodeRect are not always real. when RTL, there 'x' is top right. when draggingNodePositionMode is mouse, there x and y are mouse position. So don't calc them with their width or height. + // movingNodeOf 和 movingNodeRect并非一直如字面意义是movingNode真实坐标. RTL时, x坐标是右上角. draggingNodePositionMode是mouse时, x和y是鼠标坐标. + const movingNodeRealEl = movingNode.querySelector( + `.${options.nodeClass}` + ) as HTMLElement; // movingNode is node outer + let movingNodeOf = hp.getOffset(movingNodeRealEl); + let movingNodeRect = hp.getBoundingClientRect(movingNodeRealEl); + if (options.draggingNodePositionMode === "mouse") { + // use mouse position as dragging node position + const { moveEvent } = store; + // @ts-ignore + movingNodeOf = { x: moveEvent.pageX, y: moveEvent.pageY }; + // @ts-ignore + movingNodeRect = { x: moveEvent.clientX, y: moveEvent.clientY }; + } else if (options.rtl) { + movingNodeOf.x += movingNode.offsetWidth; + movingNodeRect.x += movingNode.offsetWidth; + } + // find tree with elementsFromPoint + let found; + let firstElement; + for (const itemEl of hp.elementsFromPoint( + movingNodeRect.x, + movingNodeRect.y + )) { + if (!firstElement) { + firstElement = itemEl; + } + if (hp.hasClass(itemEl, options.treeClass)) { + found = itemEl; + break; + } + } + // check if the found element is covered by other elements + if ( + firstElement !== found && + !hp.isDescendantOf(firstElement, found) + ) { + found = null; + } + tree = found as HTMLElement; + if (!tree) { + // out of tree or tree is covered by other elements + hooks.moveEnd("no_target_tree"); + return; + } + // check if target tree right + if ( + hooks.filterTargetTreeEl && + hooks.filterTargetTreeEl(tree, store) === false + ) { + hooks.moveEnd("disallowed_tree"); + return; + } + store.targetTreeEl = tree; + hooks.afterTargetTreeElUpdated?.(store); + const indent = hooks.getTreeIndent(store.targetTreeEl, store); + // + class DecisionInfo { + private _visibleNodesElements?: NodeList; + public get visibleNodesElementsExcludeDragging() { + if (!this._visibleNodesElements) { + this._visibleNodesElements = store.targetTreeEl.querySelectorAll( + `.${options.nodeClass}:not(.${options.draggingClassName} .${options.nodeClass})` + ); + } + return this._visibleNodesElements!; + } + + // index is for visibleNodesElementsExcludeDragging + private _closestNodeElAndIndex?: { + el: HTMLElement; + index: number; + } | null; + public get closestNodeElAndIndex() { + if (this._closestNodeElAndIndex === undefined) { + const nodes = this.visibleNodesElementsExcludeDragging; + // + if (nodes.length === 0) { + this._closestNodeElAndIndex = null; + } else { + let found, index; + const t = hp.binarySearch( + nodes, + (node) => hp.getOffset(node).y - movingNodeOf.y, + { returnNearestIfNoHit: true } + )!; + if (t.hit) { + found = t.value; + index = t.index; + } else { + if (t.greater) { + index = t.index - 1; + found = nodes[index] || t.value; + } else { + index = t.index; + found = t.value; + } + } + this._closestNodeElAndIndex = { el: found, index: index }; + } + } + return this._closestNodeElAndIndex!; + } + + // prev node is closest node when closest node is not placeholder, or is prev node of closest node when it is placeholder + // closest node不是placeholder时, prev node是closest node, 否则是closest node上方的node + private _prevNodeAndIndex?: { + el: HTMLElement; + index: number; + } | null; + public get prevNodeAndIndex() { + if (this._prevNodeAndIndex === undefined) { + let el, index; + if (this.closestNodeElAndIndex) { + index = this.closestNodeElAndIndex.index; // can't reduce 1; 不能减1 + el = this.visibleNodesElementsExcludeDragging[index]; + if ( + el && + hp.hasClass(el, options.placeholderClass) + ) { + index--; + el = this.visibleNodesElementsExcludeDragging[index]; + } + if (el) { + this._prevNodeAndIndex = { el: el, index }; + } else { + this._prevNodeAndIndex = null; + } + } else { + this._prevNodeAndIndex = null; + } + } + return this._prevNodeAndIndex; + } + + private _prevNodeOffset?: ReturnType | null; + public get prevtNodeOffset() { + if (this._prevNodeOffset === undefined) { + this._prevNodeOffset = this.prevNodeAndIndex + ? hp.getOffset(this.prevNodeAndIndex.el) + : null; + } + return this._prevNodeOffset; + } + + private _prevNodeLevel?: number | null; + public get prevNodeLevel() { + if (this._prevNodeLevel === undefined) { + this._prevNodeLevel = this.prevNodeAndIndex + ? hooks.getNodeLevelByEl(this.prevNodeAndIndex.el) + : null; + } + return this._prevNodeLevel; + } + + private _nextNodeAndIndex?: { + el: HTMLElement; + index: number; + } | null; + public get nextNodeAndIndex() { + if (this._nextNodeAndIndex === undefined) { + let el, index; + if (this.closestNodeElAndIndex) { + index = this.closestNodeElAndIndex.index + 1; + el = this.visibleNodesElementsExcludeDragging[index]; + if ( + el && + hp.hasClass(el, options.placeholderClass) + ) { + index++; + el = this.visibleNodesElementsExcludeDragging[index]; + } + if (el) { + this._nextNodeAndIndex = { el: el, index }; + } else { + this._nextNodeAndIndex = null; + } + } else { + this._nextNodeAndIndex = null; + } + } + return this._nextNodeAndIndex; + } + } + const info = new DecisionInfo(); + const onMiddleOfPrevNode = () => + movingNodeOf.y < + info.prevtNodeOffset!.y + info.prevNodeAndIndex!.el.offsetHeight / 2; + // Positive number mean moving node at left of prev node + const prevNodeLeftXReduceMovingNodeX = () => + !options.rtl + ? info.prevtNodeOffset!.x - movingNodeOf.x + : movingNodeOf.x - + (info.prevtNodeOffset!.x + info.prevNodeAndIndex!.el.offsetWidth); + const atRightOfPrevNodeIndent = () => + !options.rtl + ? movingNodeOf.x > info.prevtNodeOffset!.x + indent + : movingNodeOf.x < + info.prevtNodeOffset!.x + + info.prevNodeAndIndex!.el.offsetWidth - + indent; + // + let targetLevel: number | undefined; + + let nextNodeLevel = info.nextNodeAndIndex + ? hooks.getNodeLevelByEl(info.nextNodeAndIndex.el) + : 1; // targetLevel max is nextNodeLevel + let prevNodeAndIndex = info.prevNodeAndIndex; + if ( + !prevNodeAndIndex || + (prevNodeAndIndex.index === 0 && onMiddleOfPrevNode()) + ) { + targetLevel = 1; + prevNodeAndIndex = null; + nextNodeLevel = 1; + } else { + const atLeft = prevNodeLeftXReduceMovingNodeX(); + if (atLeft > 0) { + targetLevel = info.prevNodeLevel! - Math.ceil(atLeft / indent); + } else if (atRightOfPrevNodeIndent()) { + targetLevel = info.prevNodeLevel! + 1; + } else { + targetLevel = info.prevNodeLevel!; + } + } + if (targetLevel < nextNodeLevel) { + targetLevel = nextNodeLevel; + } + hooks.movePlaceholder(store, prevNodeAndIndex?.el, targetLevel); + }, + // @ts-ignore + beforeDrop(store: Store2) { + const { endEvent } = store; + const movingEl = store.movedElement; + const { placeholder, movedCount, targetTreeEl, startTreeEl } = store; + // destroy placeholder + const restoreStyle = () => { + hp.removeEl(placeholder); + store.updateMovedElementStyle(); + }; + // + hooks.onDrop(store, restoreStyle); + }, + }; + Object.keys(defaultOptions).forEach((key) => { + // @ts-ignore + if (options[key] === undefined) { + // @ts-ignore + options[key] = defaultOptions[key]; + } + }); + const { destroy, options: draggableHelperOptions } = draggableHelper( + treeEl, + options + ); + return { destroy, options: draggableHelperOptions, hooks }; +} diff --git a/src/examples/Base.vue b/src/examples/Base.vue deleted file mode 100644 index 406bf24..0000000 --- a/src/examples/Base.vue +++ /dev/null @@ -1,159 +0,0 @@ - - - - diff --git a/src/examples/CustomTrigger.vue b/src/examples/CustomTrigger.vue deleted file mode 100644 index 115beb0..0000000 --- a/src/examples/CustomTrigger.vue +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - diff --git a/src/examples/DragTransition.vue b/src/examples/DragTransition.vue deleted file mode 100644 index b6df328..0000000 --- a/src/examples/DragTransition.vue +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - diff --git a/src/examples/DraggablePro.vue b/src/examples/DraggablePro.vue deleted file mode 100644 index 3b4c623..0000000 --- a/src/examples/DraggablePro.vue +++ /dev/null @@ -1,134 +0,0 @@ - - - - - - diff --git a/src/examples/InScrollBox.vue b/src/examples/InScrollBox.vue deleted file mode 100644 index e824f73..0000000 --- a/src/examples/InScrollBox.vue +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - diff --git a/src/examples/NodeBack.vue b/src/examples/NodeBack.vue deleted file mode 100644 index 2e20fee..0000000 --- a/src/examples/NodeBack.vue +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - diff --git a/src/examples/RTLTree.vue b/src/examples/RTLTree.vue deleted file mode 100644 index ffbfc10..0000000 --- a/src/examples/RTLTree.vue +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - diff --git a/src/examples/ThirdCase.vue b/src/examples/ThirdCase.vue deleted file mode 100644 index 1707981..0000000 --- a/src/examples/ThirdCase.vue +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - diff --git a/src/examples/direct.html b/src/examples/direct.html deleted file mode 100644 index b2738d1..0000000 --- a/src/examples/direct.html +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - -
- -
- {{props.node.$folded ? '+' : '-'}}  -   - {{props.node.text}} -
-
-
- - - - - - - - diff --git a/src/index.js b/src/index.js deleted file mode 100644 index 5972424..0000000 --- a/src/index.js +++ /dev/null @@ -1,5 +0,0 @@ -export {default as Tree} from './components/Tree.vue' -export {default as Fold, foldAll, unfoldAll} from './plugins/fold.js' -export {default as Check} from './plugins/check.js' -export {default as Draggable} from './plugins/draggable/Draggable.vue' -export {cloneTreeData, walkTreeData, getPureTreeData} from './utils.js' diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..260d465 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,3 @@ +// export { default as BaseTree } from "./BaseTree.vue"; +export { default as Draggable } from "./draggable/Draggable.vue"; +// export { obj, BaseNode, Node } from "./types"; diff --git a/src/main.js b/src/main.js deleted file mode 100644 index 7d4fc2c..0000000 --- a/src/main.js +++ /dev/null @@ -1,11 +0,0 @@ -// The Vue build version to load with the `import` command -// (runtime-only or standalone) has been set in webpack.base.conf with an alias. -import Vue from 'vue' -import App from './App.vue' - -Vue.config.productionTip = false - -/* eslint-disable no-new */ -new Vue({ - render: h => h(App), -}).$mount('#app') diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..63eb05f --- /dev/null +++ b/src/main.ts @@ -0,0 +1,8 @@ +import Vue from 'vue' +import App from './App.vue' + +Vue.config.productionTip = false + +new Vue({ + render: h => h(App), +}).$mount('#app') diff --git a/src/plugins/check.js b/src/plugins/check.js deleted file mode 100644 index 5960e94..0000000 --- a/src/plugins/check.js +++ /dev/null @@ -1,34 +0,0 @@ -import * as ut from '../utils.js' - -export default { - props: {}, - methods: { - afterCheckChanged(node, path) { - // update parent - const nodes = this.getAllNodesByPath(path) - const reversedParents = nodes.slice(0, nodes.length - 1) - reversedParents.reverse() - for (const parent of reversedParents) { - this.$set(parent, '$checked', parent.children.every(child => child.$checked)) - } - // update children - if (node.children && node.children.length > 0) { - ut.walkTreeData(node.children, (childNode) => { - this.$set(childNode, '$checked', node.$checked) - }) - } - }, - check(node, path) { - this.$set(node, '$checked', true) - this.afterCheckChanged(node, path) - }, - uncheck(node, path) { - this.$set(node, '$checked', false) - this.afterCheckChanged(node, path) - }, - toggleCheck(node, path) { - this.$set(node, '$checked', !node.$checked) - this.afterCheckChanged(node, path) - }, - }, -} diff --git a/src/plugins/draggable/.gitignore b/src/plugins/draggable/.gitignore deleted file mode 100644 index 2ca2e9d..0000000 --- a/src/plugins/draggable/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# dev -draggable-decision-part-dev.js -_info.json diff --git a/src/plugins/draggable/Draggable.vue b/src/plugins/draggable/Draggable.vue deleted file mode 100644 index 839b75b..0000000 --- a/src/plugins/draggable/Draggable.vue +++ /dev/null @@ -1,333 +0,0 @@ - - - diff --git a/src/plugins/draggable/draggable-decision-part.js b/src/plugins/draggable/draggable-decision-part.js deleted file mode 100644 index deb562e..0000000 --- a/src/plugins/draggable/draggable-decision-part.js +++ /dev/null @@ -1,188 +0,0 @@ -import * as hp from 'helper-js' - -// arg {options, event, store, opt, info, conditions, actions, doAction} -export default function ({conditions, doAction}) { - // decision start ================================= - if (conditions['no closest'] === true){ - doAction('append to root') - } - else if (conditions['no closest'] === false){ - if (conditions['closest is top'] === true){ - if (conditions['on closest middle'] === true){ - doAction('insert before') - } - else if (conditions['on closest middle'] === false){ - if (conditions['at closest indent right'] === true){ - doAction('prepend') - } - else if (conditions['at closest indent right'] === false){ - if (conditions['closest is placeholder'] === true){ - doAction('insert after') - } - else if (conditions['closest is placeholder'] === false){ - if (conditions['closest has children excluding placeholder movingEl'] === true){ - doAction('prepend') - } - else if (conditions['closest has children excluding placeholder movingEl'] === false){ - doAction('insert after') - } - } - } - } - } - else if (conditions['closest is top'] === false){ - if (conditions['on closest middle'] === true){ - if (conditions['at closest indent right'] === false){ - if (conditions['at closest left'] === false){ - if (conditions['closest is placeholder'] === false){ - if (conditions['closest has next'] === true){ - if (conditions['closest has children excluding placeholder movingEl'] === false){ - doAction('insert after') - } - else if (conditions['closest has children excluding placeholder movingEl'] === true){ - doAction('prepend') - } - } - else if (conditions['closest has next'] === false){ - if (conditions['closest has children excluding placeholder movingEl'] === true){ - doAction('prepend') - } - else if (conditions['closest has children excluding placeholder movingEl'] === false){ - doAction('insert after') - } - } - } - else if (conditions['closest is placeholder'] === true){ - doAction('nothing') - } - } - else if (conditions['at closest left'] === true){ - if (conditions['closest is placeholder'] === true){ - if (conditions['no aboveBranch'] === true){ - doAction('nothing') - } - else if (conditions['no aboveBranch'] === false){ - doAction('after above') - } - } - else if (conditions['closest is placeholder'] === false){ - if (conditions['closest has children excluding placeholder movingEl'] === false){ - doAction('insert after') - } - else if (conditions['closest has children excluding placeholder movingEl'] === true){ - doAction('prepend') - } - } - } - } - else if (conditions['at closest indent right'] === true){ - if (conditions['closest is placeholder'] === false){ - if (conditions['closest has next'] === true){ - if (conditions['closest has children excluding placeholder movingEl'] === false){ - doAction('prepend') - } - else if (conditions['closest has children excluding placeholder movingEl'] === true){ - if (conditions['closest is top excluding placeholder'] === true){ - doAction('insert before') - } - else if (conditions['closest is top excluding placeholder'] === false){ - doAction('prepend') - } - } - } - else if (conditions['closest has next'] === false){ - doAction('prepend') - } - } - else if (conditions['closest is placeholder'] === true){ - if (conditions['no aboveBranch'] === true){ - if (conditions['closest has prev'] === false){ - doAction('nothing') - } - else if (conditions['closest has prev'] === true){ - doAction('append to prev') - } - } - else if (conditions['no aboveBranch'] === false){ - if (conditions['closest has prev'] === true){ - doAction('append to prev') - } - else if (conditions['closest has prev'] === false){ - doAction('nothing') - } - } - } - } - } - else if (conditions['on closest middle'] === false){ - if (conditions['at closest indent right'] === false){ - if (conditions['at closest left'] === false){ - if (conditions['closest is placeholder'] === false){ - if (conditions['closest has children excluding placeholder movingEl'] === true){ - doAction('prepend') - } - else if (conditions['closest has children excluding placeholder movingEl'] === false){ - doAction('insert after') - } - } - else if (conditions['closest is placeholder'] === true){ - doAction('nothing') - } - } - else if (conditions['at closest left'] === true){ - if (conditions['closest is placeholder'] === true){ - if (conditions['no aboveBranch'] === false){ - doAction('after above') - } - else if (conditions['no aboveBranch'] === true){ - doAction('nothing') - } - } - else if (conditions['closest is placeholder'] === false){ - if (conditions['closest has next'] === false){ - if (conditions['closest has children excluding placeholder movingEl'] === false){ - doAction('insert after') - } - else if (conditions['closest has children excluding placeholder movingEl'] === true){ - doAction('prepend') - } - } - else if (conditions['closest has next'] === true){ - if (conditions['closest has children excluding placeholder movingEl'] === true){ - doAction('prepend') - } - else if (conditions['closest has children excluding placeholder movingEl'] === false){ - doAction('insert after') - } - } - } - } - } - else if (conditions['at closest indent right'] === true){ - if (conditions['closest is placeholder'] === true){ - if (conditions['no aboveBranch'] === true){ - if (conditions['closest has prev'] === false){ - doAction('nothing') - } - else if (conditions['closest has prev'] === true){ - doAction('append to prev') - } - } - else if (conditions['no aboveBranch'] === false){ - if (conditions['closest has prev'] === true){ - doAction('append to prev') - } - else if (conditions['closest has prev'] === false){ - doAction('nothing') - } - } - } - else if (conditions['closest is placeholder'] === false){ - doAction('prepend') - } - } - } - } - } - // decision end ================================= -} diff --git a/src/plugins/draggable/draggable.js b/src/plugins/draggable/draggable.js deleted file mode 100644 index 2b02737..0000000 --- a/src/plugins/draggable/draggable.js +++ /dev/null @@ -1,557 +0,0 @@ -import * as hp from 'helper-js' -import draggableHelper from 'draggable-helper' -import doDraggableDecision from './draggable-decision-part.js' - -// in follow code, options belongs to makeTreeDraggable, opt belongs to draggableHelper -export default function makeTreeDraggable(treeEl, options = {}) { - options = { - // indent: 20, - // triggerClass: 'tree-node', - // triggerBySelf: false, - // unfoldWhenDragover - // unfoldWhenDragoverDelay - // draggingNodePositionMode - // getTriggerEl optional - // rootClass: 'tree-root', - // childrenClass: 'tree-children', - // branchClass: 'tree-branch', - // nodeClass: 'tree-node', - // nodeBackClass: 'tree-node-back', - // placeholderClass: 'tree-placeholder', - // placeholderNodeBackClass: 'tree-placeholder-node-back', - // placeholderNodeClass: 'tree-placeholder-node', - // draggingClass: 'dragging', - // placeholderId - // unfoldTargetNodeByEl - // getPathByBranchEl - // edgeScroll: false, - // edgeScrollTriggerMargin: 50, - // edgeScrollSpeed: 0.35, - // edgeScrollTriggerMode: 'top_left_corner', - // edgeScrol: 'top_left_corner', - // edgeScrollSpecifiedContainerX?: HTMLElement, - // edgeScrollSpecifiedContainerY?: HTMLElement, - // rtl: false - // preventTextSelection: boolean - ...options, - treeEl, - } - const {destroy, options: draggableHelperOptions} = draggableHelper(treeEl, { - triggerClassName: options.triggerClass, - triggerBySelf: options.triggerBySelf, - draggingClassName: options.draggingClass, - clone: options.cloneWhenDrag, - edgeScroll: options.edgeScroll, - edgeScrollTriggerMargin: options.edgeScrollTriggerMargin, - edgeScrollSpeed: options.edgeScrollSpeed, - edgeScrollTriggerMode: options.edgeScrollTriggerMode, - edgeScrollSpecifiedContainerX: options.edgeScrollSpecifiedContainerX, - edgeScrollSpecifiedContainerY: options.edgeScrollSpecifiedContainerY, - rtl: options.rtl, - preventTextSelection: options.preventTextSelection, - updateMovedElementStyleManually: true, - getMovedOrClonedElement: (directTriggerElement, store) => { - // find closest branch from parents - const el = hp.findParent(store.triggerElement, el => hp.hasClass(el, options.branchClass), {withSelf: true}) - return el - }, - beforeFirstMove(store, dhOptions) { - store.startTreeEl = treeEl - store.dragBranchEl = store.movedElement - store.startPath = options.getPathByBranchEl(store.movedOrClonedElement) - if (options.beforeFirstMove && options.beforeFirstMove(store, dhOptions) === false) { - return false - } - }, - beforeMove: (store, dhOptions) => { - const updatePlaceholderIndent = () => { - // set indent of placeholder - const placeholderPath = options.getPathByBranchEl(store.placeholder) - const placeholderNodeBack = store.placeholder.querySelector(`.${options.nodeBackClass}`) - placeholderNodeBack.style[!options.rtl ? 'paddingLeft' : 'paddingRight'] = (placeholderPath.length - 1) * options.indent + 'px' - // remove tempChildren if empty - if (store.tempChildren.children.length === 0) { - hp.removeEl(store.tempChildren) - } - } - // first move - // 第一次移动 - if (store.movedCount === 0) { - // create placeholder - // 创建占位元素 - const placeholder = hp.createElementFromHTML(` -
-
-
-
-
-
- `) - hp.insertAfter(placeholder, store.movedOrClonedElement) - store.placeholder = placeholder - options.afterPlaceholderCreated(store) - // create a tree children el to use when can't get childrenEl - const tempChildren = document.createElement('DIV') - hp.addClass(tempChildren, options.childrenClass) - store.tempChildren = tempChildren - // update placeholder indent. update moved element style - updatePlaceholderIndent() - store.updateMovedElementStyle() - // skip first move - // 跳过第一次移动 - return - } - // - store.updateMovedElementStyle() - // - store.oneMoveStore = {} // life cycle: one move - const movingEl = store.movedElement // branch - // find closest branch and hovering tree - let tree - const movingNode = movingEl.querySelector(`.${options.nodeClass}`) - // movingNodeOf and movingNodeRect are not always real. when RTL, there 'x' is top right. when draggingNodePositionMode is mouse, there x and y are mouse position. So don't calc them with their width or height. - // movingNodeOf 和 movingNodeRect并非一直如字面意义是movingNode真实坐标. RTL时, x坐标是右上角. draggingNodePositionMode是mouse时, x和y是鼠标坐标. - let movingNodeOf = hp.getOffset(movingNode) - let movingNodeRect = hp.getBoundingClientRect(movingNode) - if (options.draggingNodePositionMode === 'mouse') { - // use mouse position as dragging node position - const {moveEvent} = store - movingNodeOf = {x: moveEvent.pageX, y: moveEvent.pageY} - movingNodeRect = {x: moveEvent.clientX, y: moveEvent.clientY} - } else if (options.rtl) { - movingNodeOf.x += movingNode.offsetWidth - movingNodeRect.x += movingNode.offsetWidth - } - // find tree with elementsFromPoint - let found - let firstElement - for (const itemEl of hp.elementsFromPoint(movingNodeRect.x, movingNodeRect.y)) { - if (!firstElement) { - firstElement = itemEl - } - if (hp.hasClass(itemEl, options.treeClass)) { - found = itemEl - break - } - } - // check if the found element is covered by other elements - if (firstElement !== found && !hp.isDescendantOf(firstElement, found)) { - found = null - } - tree = found - if (!tree) { - // out of tree or tree is covered by other elements - return - } - // check if target tree right - if (options.filterTargetTree(tree, store, dhOptions) === false) { - return - } - store.targetTreeEl = tree - // info ======================================== - // life cycle: one move - const info = { - tree: () => tree, - root: () => info.tree.querySelector(`.${options.childrenClass}`), - closestNode: () => { - const nodes = [] // all visible nodes sort by y - const walkToGetNodes = (branch) => { - // - if (branch !== info.tree) { - const node = branch.querySelector(`.${options.nodeClass}`) - if (node && !isElementHidden(node)) { - nodes.push(node) - } - } - // - const childrenEl = branch.querySelector(`.${options.childrenClass}`) - if (childrenEl) { - for (let i = 0; i < childrenEl.children.length; i++) { - const child = childrenEl.children[i] - if (child !== movingEl && hp.hasClass(child, options.branchClass)) { - walkToGetNodes(child) - } - } - } - } - walkToGetNodes(info.tree) - // - if (nodes.length === 0) { - return - } - // - let found - const t = hp.binarySearch(nodes, (node) => hp.getOffset(node).y - movingNodeOf.y, {returnNearestIfNoHit: true}) - if (t.hit) { - found = t.value - } else { - if (t.greater) { - found = nodes[t.index - 1] || t.value - } else { - found = t.value - } - } - return found - }, - closestNodeOffset: () => hp.getOffset(info.closestNode), - closestBranch: () => hp.findParent(info.closestNode, el => hp.hasClass(el, options.branchClass)), - closestNext: () => { - let next = info.closestBranch.nextSibling - while (next) { - if (next !== movingEl && hp.hasClass(next, options.branchClass) && !isElementHidden(next)) { - return next - } - next = next.nextSibling - } - }, - closestPrev: () => { - let prev = info.closestBranch.previousSibling - while (prev) { - if (prev !== movingEl && hp.hasClass(prev, options.branchClass) && !isElementHidden(prev)) { - return prev - } - prev = prev.previousSibling - } - }, - aboveBranch: () => { - // find above from branch to root - // closestBranch must be placeholder - if (info.closestBranch !== store.placeholder) { - return - } - if (conditions['closest has next']) { - return - } - // find placeholder prev or parent - let cur = info.closestBranch - let prev = cur.previousSibling - let found - while (prev) { - if (prev !== movingEl && hp.hasClass(prev, options.branchClass) && !isElementHidden(prev)) { - cur = prev - found = true - break - } - prev = prev.previousSibling - } - if (!found) { - cur = hp.findParent(cur, el => hp.hasClass(el, options.branchClass)) - } - // - while (cur) { - const curNode = cur.querySelector(`.${options.nodeClass}`) - if (!options.rtl) { - if (hp.getOffset(curNode).x <= movingNodeOf.x) { - break - } - } else { - if (hp.getOffset(curNode).x + curNode.offsetWidth >= movingNodeOf.x) { - break - } - } - let hasNextBranch - let t = cur.nextSibling - while (t) { - if (t !== movingEl && t !== store.placeholder && hp.hasClass(t, options.branchClass) && !isElementHidden(t)) { - hasNextBranch = true - break - } - t = t.nextSibling - } - if (hasNextBranch) { - break - } - const parent = hp.findParent(cur, el => hp.hasClass(el, options.branchClass)) - if (!parent) { - break - } - cur = parent - } - return cur - }, - } - // conditions ======================================== - // life cycle: one move - const conditions = { - 'no closest': () => !info.closestNode, - 'closest is top': () => info.closestBranch === hp.findNodeList(info.root.children, el => el !== movingEl && !isElementHidden(el)), - 'closest is top excluding placeholder': () => info.closestBranch === hp.findNodeList(info.root.children, el => el !== movingEl && el !== store.placeholder && !isElementHidden(el)), - 'on closest middle': () => movingNodeOf.y < info.closestNodeOffset.y + info.closestNode.offsetHeight / 2, - 'at closest indent right': () => movingNodeOf.x > info.closestNodeOffset.x + options.indent, - 'at closest left': () => movingNodeOf.x < info.closestNodeOffset.x, - 'closest is placeholder': () => info.closestBranch === store.placeholder, - 'no aboveBranch': () => !info.aboveBranch, - 'closest has next': () => info.closestNext, - 'closest has prev': () => info.closestPrev, - 'closest has children excluding placeholder movingEl': () => { - const childrenEl = info.closestBranch.querySelector(`.${options.childrenClass}`) - if (childrenEl) { - return hp.findNodeList(childrenEl.children, el => el !== movingEl && el !== store.placeholder && !isElementHidden(el)) - } - }, - } - // fix for rtl - if (options.rtl) { - Object.assign(conditions, { - 'at closest indent right': () => movingNodeOf.x < info.closestNodeOffset.x + info.closestNode.offsetWidth - options.indent, // at indent left - 'at closest left': () => movingNodeOf.x > info.closestNodeOffset.x + info.closestNode.offsetWidth, // at right - }) - } - // convert conditions result to Boolean - Object.keys(conditions).forEach(key => { - const old = conditions[key] - conditions[key] = function () { - return Boolean(old.call(this)) - } - }) - // - hp.attachCache(info, info) - hp.attachCache(conditions, conditions) - store.oneMoveStore.info = info - store.oneMoveStore.conditions = conditions - // actions start ======================================== - const doAction = (name, ...args) => { - if (!store._doActionQueue) { - store._doActionQueue = Promise.resolve() - } - const queue = store._doActionQueue - store._doActionQueue = queue.then(async () => { - // record tried actions in one move - if (!store.oneMoveStore.actionRecords) { - store.oneMoveStore.actionRecords = [] - } - const {actionRecords} = store.oneMoveStore - // - const action = actions[name] - const r = action(...args) - actionRecords.push(name) - await r - updatePlaceholderIndent() - }) - } - const actions = { - async 'nothing'() {}, // do nothing - async 'append to root'() { - // no closest branch, just append to root - if (options.isTargetTreeRootDroppable(store)) { - hp.appendTo(store.placeholder, info.root) - } - }, - async 'insert before'() { - if (options.isNodeParentDroppable(info.closestBranch, store.targetTreeEl)) { - hp.insertBefore(store.placeholder, info.closestBranch) - } else { - return secondCase(getParentBranchByEl(info.closestBranch)) - } - }, - async 'insert after'(branch = info.closestBranch) { - if (options.isNodeParentDroppable(branch, store.targetTreeEl)) { - hp.insertAfter(store.placeholder, branch) - } else { - const moved = await secondCase(getParentBranchByEl(branch)) - const isFirstTriedAction = !store.oneMoveStore.actionRecords || store.oneMoveStore.actionRecords.length === 1 - if (!moved && isFirstTriedAction) { - return thirdCase(branch) - } - } - }, - async prepend() { - if (info.closestBranch === store.placeholder) { - return - } - if (options.ifNodeFolded(info.closestBranch, store) && !options.unfoldWhenDragover) { - return doAction('insert after', info.closestBranch) - } else { - if (options.isNodeDroppable(info.closestBranch, store.targetTreeEl)) { - await tryUnfoldAndPrepend(info.closestBranch) - } else { - return secondCase(info.closestBranch) - } - } - }, - async 'after above'() { - if (options.isNodeParentDroppable(info.aboveBranch, store.targetTreeEl)) { - hp.insertAfter(store.placeholder, info.aboveBranch) - } else { - return secondCase(getParentBranchByEl(info.aboveBranch)) - } - }, - async 'append to prev'() { - if (info.closestPrev === store.placeholder) { - return - } - if (options.ifNodeFolded(info.closestPrev, store)) { - return doAction('insert after', info.closestPrev) - } else { - if (options.isNodeDroppable(info.closestPrev, store.targetTreeEl)) { - const childrenEl = await unfoldAndGetChildrenEl(info.closestPrev) - hp.appendTo(store.placeholder, childrenEl) - } else { - return secondCase(info.closestPrev) - } - } - }, - } - // second case for actions, when target position not droppable - // return true if moved - const secondCase = async (branchEl) => { - if (branchEl) { - const targetEl = options._findClosestDroppablePosition(branchEl, store.targetTreeEl) - if (targetEl) { - hp.insertAfter(store.placeholder, targetEl) - return true - } - } - } - // when action is after, first case and second case invalid, try prepend - // 当操作是'after', 第一种第二种情况无效时, 尝试prepend - const thirdCase = async (branchEl) => { - // the third case - if (!options.ifNodeFolded(branchEl, store) && options.isNodeDroppable(branchEl, store.targetTreeEl)) { - await tryUnfoldAndPrepend(branchEl) - } - } - const unfoldAndGetChildrenEl = async (branch) => { - await options.unfoldTargetNodeByEl(branch, store) - let childrenEl = branch.querySelector(`.${options.childrenClass}`) - if (!childrenEl) { - childrenEl = store.tempChildren - hp.appendTo(childrenEl, branch) - } - return childrenEl - } - const tryUnfoldAndPrepend = async (branchEl) => { - const func = async () => { - const childrenEl = await unfoldAndGetChildrenEl(branchEl) - hp.prependTo(store.placeholder, childrenEl) - } - if (options.ifNodeFolded(branchEl, store)) { - // delay if node folded - let oneMoveStore = store.oneMoveStore - setTimeout(() => { - // check if expired - if (oneMoveStore === store.oneMoveStore) { - func() - } - }, options.unfoldWhenDragoverDelay) - } else { - await func() - } - } - // actions end ======================================== - doDraggableDecision({options, event: store.moveEvent, store, opt: dhOptions, info, conditions, actions, doAction}) - }, - afterMove: (store, dhOptions) => { - options.afterMove && options.afterMove(store, dhOptions) - }, - beforeDrop: async (store, dhOptions) => { - const {endEvent} = store - const movingEl = store.movedElement // branch - const {placeholder, tempChildren, movedCount, targetTreeEl, startTreeEl} = store - // use mask tree to avoid flick caused by DOM update in short time - // 复制 targetTreeEl 作为遮罩, 避免短时间内更新DOM引起的闪烁 - let maskTree, maskTree2 - if (targetTreeEl) { - // No targetTreeEl mean no valid move. - // targetTreeEl不存在意味着没有有效移动. - - // create mask tree - maskTree = targetTreeEl.cloneNode(true) - targetTreeEl.style.display = 'none' - hp.insertAfter(maskTree, targetTreeEl) - if (startTreeEl !== targetTreeEl) { - maskTree2 = startTreeEl.cloneNode(true) - startTreeEl.style.display = 'none' - hp.insertAfter(maskTree2, startTreeEl) - } - // - store.placeholderPath = options.getPathByBranchEl(placeholder) - store.targetPath = getTargetPath() - let pathChanged = targetTreeEl === startTreeEl && store.targetPath.toString() !== store.startPath.toString() - store.pathChangePrevented = false - if (options.beforeDrop && options.beforeDrop(pathChanged, store, dhOptions) === false) { - pathChanged = false - store.pathChangePrevented = false - } - store.pathChanged = pathChanged - } - // destroy placeholder and tempChildren - hp.removeEl(placeholder) - if (tempChildren) { - hp.removeEl(tempChildren) - } - store.updateMovedElementStyle() - // - await options.afterDrop(store, dhOptions) - // remove mask tree - if (maskTree) { - await hp.waitTime(0) - hp.removeEl(maskTree) - targetTreeEl.style.display = 'block' - if (maskTree2) { - hp.removeEl(maskTree2) - startTreeEl.style.display = 'block' - } - } - function getTargetPath() { - // example - // startPath placeholderPath - // [0] [1] - // [0] [1, 0] - // [3, 1] [3, 3] - // [3, 1] [3, 3, 5] - // above targetPaths should be [0], [0, 0] [3, 2] [3, 2, 5] - const {startTree, targetTree, startPath, placeholderPath} = store - const targetPath = placeholderPath.slice(0) - if (options.cloneWhenDrag !== true) { - if (startTree === targetTree) { - if (startPath.length <= targetPath.length) { - const sw = startPath.slice(0, startPath.length - 1) // without end - const tw = targetPath.slice(0, sw.length) // same length with sw - if (sw.toString() === tw.toString()) { - const endIndex = sw.length - if (startPath[endIndex] < targetPath[endIndex]) { - targetPath[endIndex] -= 1 - } else if (startPath[endIndex] === targetPath[endIndex]) { - // position not changed - } - } - } - } - } - return targetPath - } - }, - }) - return {destroy, options, optionsUpdated} - function getParentBranchByEl(el) { - return hp.findParent(el, el => { - if (hp.hasClass(el, options.branchClass)) { - return true - } - if (hp.hasClass(el, options.rootClass)) { - return 'break' - } - }) - } - function optionsUpdated() { - Object.assign(draggableHelperOptions, { - triggerClassName: options.triggerClass, - triggerBySelf: options.triggerBySelf, - draggingClassName: options.draggingClass, - clone: options.cloneWhenDrag, - // edgeScroll - edgeScroll: options.edgeScroll, - edgeScrollTriggerMargin: options.edgeScrollTriggerMargin, - edgeScrollSpeed: options.edgeScrollSpeed, - edgeScrollTriggerMode: options.edgeScrollTriggerMode, - // - rtl: options.rtl, - preventTextSelection: options.preventTextSelection, - }) - } -} - -function isElementHidden(el) { - return el.offsetWidth === 0 && el.offsetHeight === 0 -} diff --git a/src/plugins/fold.js b/src/plugins/fold.js deleted file mode 100644 index 331479c..0000000 --- a/src/plugins/fold.js +++ /dev/null @@ -1,65 +0,0 @@ -import Vue from 'vue' -import { walkTreeData } from "../utils"; - -export function foldAll(treeData) { - walkTreeData(treeData, childNode => { - Vue.set(childNode, '$folded', true) - }) -} -export function unfoldAll(treeData) { - walkTreeData(treeData, childNode => { - Vue.set(childNode, '$folded', false) - }) -} - -export default { - props: { - foldingTransitionName: {type: String}, - foldingTransition: {}, - foldAllAfterMounted: {type: Boolean}, - }, - methods: { - fold(node, path) { - if (!node.$folded) { - this.$set(node, '$folded', true) - this.$emit('nodeFoldedChanged', node) - } - }, - unfold(node, path, opt = {}) { - opt = { - foldOthers: false, - ...opt, - } - if (opt.foldOthers) { - this.foldAll() - } - if (node.$folded) { - this.$set(node, '$folded', false) - this.$emit('nodeFoldedChanged', node) - this.$emit('node-folded-changed', node) - } - }, - toggleFold(node, path, opt) { - if (node.$folded) { - this.unfold(node, path, opt) - } else { - this.fold(node, path, opt) - } - }, - foldAll() { - this.walkTreeData((childNode) => { - this.fold(childNode) - }) - }, - unfoldAll() { - this.walkTreeData((childNode) => { - this.unfold(childNode, {unfoldParent: false}) - }) - }, - }, - mounted() { - if (this.foldAllAfterMounted) { - this.foldAll() - } - }, -} diff --git a/src/shims-tsx.d.ts b/src/shims-tsx.d.ts new file mode 100644 index 0000000..c656c68 --- /dev/null +++ b/src/shims-tsx.d.ts @@ -0,0 +1,13 @@ +import Vue, { VNode } from 'vue' + +declare global { + namespace JSX { + // tslint:disable no-empty-interface + interface Element extends VNode {} + // tslint:disable no-empty-interface + interface ElementClass extends Vue {} + interface IntrinsicElements { + [elem: string]: any + } + } +} diff --git a/src/shims-vue.d.ts b/src/shims-vue.d.ts new file mode 100644 index 0000000..d9f24fa --- /dev/null +++ b/src/shims-vue.d.ts @@ -0,0 +1,4 @@ +declare module '*.vue' { + import Vue from 'vue' + export default Vue +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..f3fd124 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,22 @@ +export type obj = Record; // equal to object + +export interface BaseNode { + $id: string | number; + $pid?: string | number; + $level: number; // 0 is root + $hidden?: boolean; + $folded?: boolean; + $checked?: boolean | 0; + $children: Node[]; + $childrenLoading?: boolean; + $childrenLoadStaus?: obj; // private + $draggable?: boolean; + $droppable?: boolean; + // style + $nodeStyle?: string | Record | unknown; + $nodeClass?: string | unknown; + $outerStyle?: string | Record | unknown; + $outerClass?: string | unknown; +} + +export type Node = obj & BaseNode; diff --git a/src/utils.js b/src/utils.js deleted file mode 100644 index 746cfa2..0000000 --- a/src/utils.js +++ /dev/null @@ -1,22 +0,0 @@ -import {TreeData} from 'helper-js' - -export function cloneTreeData(treeData, opt) { - return (new TreeData(treeData)).clone(opt) -} - -export function walkTreeData(treeData, handler, opt) { - return (new TreeData(treeData)).walk(handler, opt) -} - -export function getPureTreeData(treeData) { - const opt = { - afterNodeCreated: newNode => { - Object.keys(newNode).forEach(key => { - if (key[0] === '$') { - delete newNode[key] - } - }) - }, - } - return cloneTreeData(treeData, opt) -} diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 0000000..3cda283 --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,98 @@ +import * as hp from "helper-js"; +import { obj, BaseNode } from "./types"; + +export function genNodeID() { + return `ht_${hp.randString(12)}`; +} + +export function initNode(node: obj) { + if (!node.$id) { + node.$id = genNodeID(); + } + if (!node.$children) { + node.$children = []; + } +} + +export function convertTreeDataToFlat( + data: T[], + childrenKey = "children", + idKey = "id" +) { + const flatData: T[] = []; + const mapForPid = new Map(); + hp.walkTreeData( + data, + (node, index, parent) => { + const newNode = { $id: node[idKey], $pid: "", ...node }; + initNode(newNode); + mapForPid.set(node, newNode.$id); + newNode.$pid = (parent && mapForPid.get(parent)) || null; + flatData.push(newNode); + }, + childrenKey + ); + return convertFlatDataToStandard(flatData, "$id", "$pid"); +} + +export function convertFlatDataToStandard( + data: T[], + idKey = "id", + pidKey = "parent_id" +) { + const nodesByID: Record = {}; + let nodes = data.map((node) => { + // @ts-ignore + const newNode: T & BaseNode = { + $id: node[idKey], + $pid: node[pidKey], + ...node, + $children: [], + }; + initNode(newNode); + nodesByID[newNode.$id] = newNode; + return newNode; + }); + const top = []; + for (const node of nodes) { + if (node.$level == null) { + node.$level = resolveLevel(node); + } + const parent = node.$pid && nodesByID[node.$pid]; + if (parent) { + parent.$children.push(node); + } + if (node.$level === 1) { + top.push(node); + } + } + nodes = []; + hp.walkTreeData( + top, + (node) => { + nodes.push(node); + }, + "$children" + ); + return { nodes, nodesByID }; + // + function resolveLevel(node: T & BaseNode): number { + if (node.$level && node.$level > 0) { + return node.$level; + } else { + const parent = nodesByID[node.$pid || ""]; + if (!parent) { + return 1; + } else { + return resolveLevel(parent) + 1; + } + } + } +} + +export function getOuterHeight(el: Element) { + return ( + hp.getBoundingClientRect(el).height + + hp.getOuterAttachedWidth(el, { margin: true, border: false }) + ); +} diff --git a/tests/unit/example.spec.js b/tests/unit/example.spec.js deleted file mode 100644 index c585ea3..0000000 --- a/tests/unit/example.spec.js +++ /dev/null @@ -1,13 +0,0 @@ -import { expect } from 'chai' -import { shallowMount } from '@vue/test-utils' -import HelloWorld from '@/components/HelloWorld.vue' - -describe('HelloWorld.vue', () => { - it('renders props.msg when passed', () => { - const msg = 'new message' - const wrapper = shallowMount(HelloWorld, { - propsData: { msg } - }) - expect(wrapper.text()).to.include(msg) - }) -}) diff --git a/tsconfig.json b/tsconfig.json index bb22a0c..a6fbee1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,33 +7,24 @@ "importHelpers": true, "moduleResolution": "node", "experimentalDecorators": true, + "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "sourceMap": true, "baseUrl": ".", - "types": [ - ], + "declaration": true, + "types": ["webpack-env"], "paths": { - "@/*": [ - "src/*" - ] + "@/*": ["src/*"] }, - "lib": [ - "esnext", - "dom", - "dom.iterable", - "scripthost" - ] + "lib": ["esnext", "dom", "dom.iterable", "scripthost"] }, "include": [ - "types/*.ts", "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx" ], - "exclude": [ - "node_modules" - ] + "exclude": ["node_modules"] } diff --git a/types/index.d.ts b/types/index.d.ts deleted file mode 100644 index af17655..0000000 --- a/types/index.d.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { Component, Vue, Prop, Emit } from 'vue-property-decorator' -import {VNode} from 'vue' -import * as dh from "draggable-helper"; - -interface Node { - [propName: string]: any - children?: Node[] - $hidden?: boolean - $branchClass?: any - $nodeBackClass?: any - $nodeClass?: any - $childrenClass?: any - $branchStyle?: any - $nodeBackStyle?: any - $nodeStyle?: any - $childrenStyle?: any - $folded?: boolean - $checked?: boolean - $draggable?(currentPath: Path, tree: Tree, store: Store): IsDraggableOrIsDroppable - $droppable?(currentPath: Path, tree: Tree, store: Store): IsDraggableOrIsDroppable -} -type TreeData = Node[] -type Path = number[] - -interface iteratePathOptions { - reverse: boolean -} -interface Trees { - [treeId: string]: Vue -} -type overrideSlotDefault_arg0 = {node: Node, index: number, path: Path, tree: Tree} -// the original vnodes if this.overrideSlotDefault is not defined -interface VNodeFunc{ - (): VNode -} -// interface overrideSlotDefault{ -// (info: overrideSlotDefault_arg0, original: VNodeFunc): any -// } -export class Tree extends Vue{ - @Prop() - value: TreeData - get treeData(): TreeData // alias of this.value - set treeData(value: TreeData) // emit 'input' event - // Declared as computed property setter - @Prop({ default: 20 }) - indent: number - @Prop() - rtl: boolean // direction=rtl - @Prop({ default: {} }) - rootNode: Node - // data - trees: Trees - treeClass: string - treeId: string - // methods - iteratePath(path: Path, opt?: iteratePathOptions): IterableIterator<[Path, Node]> - getTreeVmByTreeEl(treeEl: HTMLElement): Vue - getAllNodesByPath(path: Path): Node[] - getNodeByPath(path: Path): Node - getPathByBranchEl(branchEl: HTMLElement): Path - getBranchElByPath(path: Path): HTMLElement - getBranchElByPath(path: Path): HTMLElement - getPathByBranchEl(branchEl: HTMLElement): Node - getNodeParentByPath(path: Path): Node - removeNodeByPath(path: Path): Node - walkTreeData(callback: walkTreeDataCallback, options?: {reverse: boolean}): void - cloneTreeData(options?: cloneTreeDataOptions): TreeData - // remove key which starts with '$ - getPureTreeData(): TreeData - // hooks. in data not in props, so you only can set it by extend or mixins, and override it - // overrideSlotDefault?: overrideSlotDefault - // blockHeader?: VNodeFunc - // blockFooter?: VNodeFunc -} - -interface unfoldOptions { - foldOthers: boolean -} -// plugins ======================== -export class Fold extends Vue{ - @Prop() - foldingTransitionName: string - @Prop() - foldingTransition: Vue - @Prop() - foldAllAfterMounted: boolean - // methods - fold(node: Node, path: Path): void - unfold(node: Node, path: Path, opt?:unfoldOptions): void - toggleFold(node: Node, path: Path, opt?:unfoldOptions): void - foldAll(): void - unfoldAll(): void -} - -export interface foldAll { - (treeData: TreeData): void -} - -export interface unfoldAll { - (treeData: TreeData): void -} - -export class Check extends Vue{ - // methods - check(node: Node, path: Path): void - uncheck(node: Node, path: Path): void - toggleCheck(node: Node, path: Path): void -} -type IsDraggableOrIsDroppable = boolean | undefined -// darg info store -interface Store extends dh.Store{ - startTreeEl?: HTMLElement - startTree?: Vue - startPath?: Path - dragBranchEl?: HTMLElement - dragNode?: Node - targetTreeEl?: HTMLElement - targetTree?: Vue - targetPath?: Path - targetPathNotEqualToStartPath?: boolean - placeholder?: HTMLElement - pathChangePrevented?: boolean - pathChanged?: boolean -} -interface prop_draggable_droppable{ - (tree: Tree, store: Store): IsDraggableOrIsDroppable -} -interface prop_eachDraggable_eachDroppable{ - (currentPath: Path, tree: Tree, store: Store): IsDraggableOrIsDroppable -} -interface prop_ondragstart_ondragend{ - // return false to prevent - (tree: Tree, store: Store): false|any -} -export class Draggable extends Vue{ - @Prop({default: 'tree-node'}) - triggerClass: string - @Prop() - triggerBySelf: boolean - @Prop({default: true}) - draggable: boolean | prop_draggable_droppable - @Prop({default: true}) - droppable: boolean | prop_draggable_droppable - @Prop() - eachDraggable: prop_eachDraggable_eachDroppable - @Prop() - eachDroppable: prop_eachDraggable_eachDroppable - @Prop() - ondragstart: prop_ondragstart_ondragend - @Prop() - ondragend: prop_ondragstart_ondragend - @Prop({default: true}) - unfoldWhenDragover: boolean - @Prop({default: 30}) - unfoldWhenDragoverDelay: number - @Prop({default: 'top_left_corner'}) - draggingNodePositionMode: 'top_left_corner'|'mouse' - @Prop() - edgeScroll: boolean - @Prop({default: 50}) - edgeScrollTriggerMargin: number - @Prop({default: 0.35}) - edgeScrollSpeed: number - @Prop({default: 'top_left_corner'}) - edgeScrollTriggerMode: dh.Options['edgeScrollTriggerMode'] - @Prop() - edgeScrollSpecifiedContainerX: dh.Options['edgeScrollSpecifiedContainerX'] - @Prop() - edgeScrollSpecifiedContainerY: dh.Options['edgeScrollSpecifiedContainerY'] - // data - treesStore: {store: Store} // just for get the darg info store - // methods -} - -// utils ====================== -interface cloneTreeDataOptions{ - afterNodeCreated(newNode: object, info: {oldNode: object, index: number, parent: object, path: Path}): void -} -export function cloneTreeData(treeData: TreeData, options?: cloneTreeDataOptions): TreeData - -type walkTreeDataCallbackReturn = void|false|'skip children'|'skip siblings' -interface walkTreeDataCallback { - (node: Node, index: number, parent: object|null, path:number[]): walkTreeDataCallbackReturn -} -export function walkTreeData(treeData: TreeData, callback: walkTreeDataCallback, options?: {reverse: boolean}): void - -// remove key which starts with '$ -export function getPureTreeData(treeData: TreeData): TreeData \ No newline at end of file diff --git a/vue.config.js b/vue.config.js deleted file mode 100644 index 9d58086..0000000 --- a/vue.config.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - transpileDependencies: ['helper-js', 'draggable-helper', 'vue-functions', 'drag-event-service'], -} \ No newline at end of file