diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index b0d7fd91b..000000000 --- a/.editorconfig +++ /dev/null @@ -1,12 +0,0 @@ -# editorconfig.org -root = true - -[*] -indent_style = tab -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[*.md] -trim_trailing_whitespace = false diff --git a/.gitignore b/.gitignore index 434cfa9b1..40b878db5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1 @@ -node_modules -mock.png -.*.sw* -.build* -jquery.fn.* +node_modules/ \ No newline at end of file diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 3f67a098b..000000000 --- a/.jshintrc +++ /dev/null @@ -1,24 +0,0 @@ -{ - "strict": true, - "newcap": false, - "node": true, - "expr": true, - "supernew": true, - "laxbreak": true, - "white": true, - "globals": { - "define": true, - "test": true, - "expect": true, - "module": true, - "asyncTest": true, - "start": true, - "ok": true, - "equal": true, - "notEqual": true, - "deepEqual": true, - "window": true, - "document": true, - "performance": true - } -} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index dba06578d..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,18 +0,0 @@ -# Contribution Guidelines - - -### Issue - - 1. Try [dev](https://github.com/RubaXa/Sortable/tree/dev/)-branch, perhaps the problem has been solved; - 2. [Use the search](https://github.com/RubaXa/Sortable/search?q=problem), maybe already have an answer; - 3. If not found, create example on [jsbin.com (draft)](http://jsbin.com/zunibaxada/1/edit?html,js,output) and describe the problem. - - ---- - - -### Pull Request - - 1. Before PR run `grunt`; - 2. Only into [dev](https://github.com/RubaXa/Sortable/tree/dev/)-branch. - diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100755 index 5d67184bb..000000000 --- a/Gruntfile.js +++ /dev/null @@ -1,103 +0,0 @@ -module.exports = function (grunt) { - 'use strict'; - - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - - version: { - js: { - src: ['<%= pkg.exportName %>.js', '*.json'] - }, - cdn: { - options: { - prefix: '(cdnjs\\.cloudflare\\.com\\/ajax\\/libs\\/Sortable|cdn\\.jsdelivr\\.net\\/sortable)\\/', - replace: '[0-9\\.]+' - }, - src: ['README.md'] - } - }, - - jshint: { - all: ['*.js', '!*.min.js'], - - options: { - jshintrc: true - } - }, - - uglify: { - options: { - banner: '/*! <%= pkg.exportName %> <%= pkg.version %> - <%= pkg.license %> | <%= pkg.repository.url %> */\n' - }, - dist: { - files: { - '<%= pkg.exportName %>.min.js': ['<%= pkg.exportName %>.js'] - } - }, - jquery: { - files: {} - } - }, - - exec: { - 'meteor-test': { - command: 'meteor/runtests.sh' - }, - 'meteor-publish': { - command: 'meteor/publish.sh' - } - }, - - jquery: {} - }); - - - grunt.registerTask('jquery', function (exportName, uglify) { - if (exportName == 'min') { - exportName = null; - uglify = 'min'; - } - - if (!exportName) { - exportName = 'sortable'; - } - - var fs = require('fs'), - filename = 'jquery.fn.' + exportName + '.js'; - - grunt.log.oklns(filename); - - fs.writeFileSync( - filename, - (fs.readFileSync('jquery.binding.js') + '') - .replace('$.fn.sortable', '$.fn.' + exportName) - .replace('/* CODE */', - (fs.readFileSync('Sortable.js') + '') - .replace(/^[\s\S]*?function[\s\S]*?(var[\s\S]+)\/\/\s+Export[\s\S]+/, '$1') - ) - ); - - if (uglify) { - var opts = {}; - - opts['jquery.fn.' + exportName + '.min.js'] = filename; - grunt.config.set('uglify.jquery.files', opts); - - grunt.task.run('uglify:jquery'); - } - }); - - - grunt.loadNpmTasks('grunt-version'); - grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-contrib-uglify'); - grunt.loadNpmTasks('grunt-exec'); - - // Meteor tasks - grunt.registerTask('meteor-test', 'exec:meteor-test'); - grunt.registerTask('meteor-publish', 'exec:meteor-publish'); - grunt.registerTask('meteor', ['meteor-test', 'meteor-publish']); - - grunt.registerTask('tests', ['jshint']); - grunt.registerTask('default', ['tests', 'version', 'uglify:dist']); -}; diff --git a/README.md b/README.md deleted file mode 100644 index c90775fb5..000000000 --- a/README.md +++ /dev/null @@ -1,661 +0,0 @@ -# Sortable -Sortable is a minimalist JavaScript library for reorderable drag-and-drop lists. - -Demo: http://rubaxa.github.io/Sortable/ - - -## Features - - * Supports touch devices and [modern](http://caniuse.com/#search=drag) browsers (including IE9) - * Can drag from one list to another or within the same list - * CSS animation when moving items - * Supports drag handles *and selectable text* (better than voidberg's html5sortable) - * Smart auto-scrolling - * Built using native HTML5 drag and drop API - * Supports [Meteor](meteor/README.md), [AngularJS](#ng) and [React](#react) - * Supports any CSS library, e.g. [Bootstrap](#bs) - * Simple API - * [CDN](#cdn) - * No jQuery (but there is [support](#jq)) - - -
- - -### Articles - * [Sortable v1.0 — New capabilities](https://github.com/RubaXa/Sortable/wiki/Sortable-v1.0-—-New-capabilities/) (December 22, 2014) - * [Sorting with the help of HTML5 Drag'n'Drop API](https://github.com/RubaXa/Sortable/wiki/Sorting-with-the-help-of-HTML5-Drag'n'Drop-API/) (December 23, 2013) - - -
- - -### Usage -```html - -``` - -```js -var el = document.getElementById('items'); -var sortable = Sortable.create(el); -``` - -You can use any element for the list and its elements, not just `ul`/`li`. Here is an [example with `div`s](http://jsbin.com/luxero/2/edit?html,js,output). - - ---- - - -### Options -```js -var sortable = new Sortable(el, { - group: "name", // or { name: "...", pull: [true, false, clone], put: [true, false, array] } - sort: true, // sorting inside list - delay: 0, // time in milliseconds to define when the sorting should start - disabled: false, // Disables the sortable if set to true. - store: null, // @see Store - animation: 150, // ms, animation speed moving items when sorting, `0` — without animation - handle: ".my-handle", // Drag handle selector within list items - filter: ".ignore-elements", // Selectors that do not lead to dragging (String or Function) - draggable: ".item", // Specifies which items inside the element should be sortable - ghostClass: "sortable-ghost", // Class name for the drop placeholder - dataIdAttr: 'data-id', - - scroll: true, // or HTMLElement - scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling. - scrollSpeed: 10, // px - - setData: function (dataTransfer, dragEl) { - dataTransfer.setData('Text', dragEl.textContent); - }, - - // dragging started - onStart: function (/**Event*/evt) { - evt.oldIndex; // element index within parent - }, - - // dragging ended - onEnd: function (/**Event*/evt) { - evt.oldIndex; // element's old index within parent - evt.newIndex; // element's new index within parent - }, - - // Element is dropped into the list from another list - onAdd: function (/**Event*/evt) { - var itemEl = evt.item; // dragged HTMLElement - evt.from; // previous list - // + indexes from onEnd - }, - - // Changed sorting within list - onUpdate: function (/**Event*/evt) { - var itemEl = evt.item; // dragged HTMLElement - // + indexes from onEnd - }, - - // Called by any change to the list (add / update / remove) - onSort: function (/**Event*/evt) { - // same properties as onUpdate - }, - - // Element is removed from the list into another list - onRemove: function (/**Event*/evt) { - // same properties as onUpdate - }, - - // Attempt to drag a filtered element - onFilter: function (/**Event*/evt) { - var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event. - }, - - // Event when you move an item in the list or between lists - onMove: function (/**Event*/evt) { - // Example: http://jsbin.com/tuyafe/1/edit?js,output - evt.dragged; // dragged HTMLElement - evt.draggedRect; // TextRectangle {left, top, right и bottom} - evt.related; // HTMLElement on which have guided - evt.relatedRect; // TextRectangle - // retrun false; — for cancel - } -}); -``` - - ---- - - -#### `group` option -To drag elements from one list into another, both lists must have the same `group` value. -You can also define whether lists can give away, give and keep a copy (`clone`), and receive elements. - - * name: `String` — group name - * pull: `true|false|'clone'` — ability to move from the list. `clone` — copy the item, rather than move. - * put: `true|false|["foo", "bar"]` — whether elements can be added from other lists, or an array of group names from which elements can be taken. Demo: http://jsbin.com/naduvo/2/edit?html,js,output - - ---- - - -#### `sort` option -Sorting inside list. - -Demo: http://jsbin.com/xizeh/2/edit?html,js,output - - ---- - - -#### `delay` option -Time in milliseconds to define when the sorting should start. - -Demo: http://jsbin.com/xizeh/4/edit?html,js,output - - ---- - - -#### `disabled` options -Disables the sortable if set to `true`. - -Demo: http://jsbin.com/xiloqu/1/edit?html,js,output - -```js -var sortable = Sortable.create(list); - -document.getElementById("switcher").onclick = function () { - var state = sortable.option("disabled"); // get - - sortable.option("disabled", !state); // set -}; -``` - - ---- - - -#### `handle` option -To make list items draggable, Sortable disables text selection by the user. -That's not always desirable. To allow text selection, define a drag handler, -which is an area of every list element that allows it to be dragged around. - -Demo: http://jsbin.com/newize/1/edit?html,js,output - -```js -Sortable.create(el, { - handle: ".my-handle" -}); -``` - -```html - -``` - -```css -.my-handle { - cursor: move; - cursor: -webkit-grabbing; -} -``` - - ---- - - -#### `filter` option - - -```js -Sortable.create(list, { - filter: ".js-remove, .js-edit", - onFilter: function (evt) { - var item = evt.item, - ctrl = evt.target; - - if (Sortable.utils.is(ctrl, ".js-remove")) { // Click on remove button - item.parentNode.removeChild(item); // remove sortable item - } - else if (Sortable.utils.is(ctrl, ".js-edit")) { // Click on edit link - // ... - } - } -}) -``` - - ---- - - -#### `ghostClass` option -Class name for the drop placeholder. - -Demo: http://jsbin.com/hunifu/1/edit?css,js,output - -```css -.ghost { - opacity: 0.4; -} -``` - -```js -Sortable.create(list, { - ghostClass: "ghost" -}); -``` - - ---- - - -#### `scroll` option -If set to `true`, the page (or sortable-area) scrolls when coming to an edge. - -Demo: - - `window`: http://jsbin.com/boqugumiqi/1/edit?html,js,output - - `overflow: hidden`: http://jsbin.com/kohamakiwi/1/edit?html,js,output - - ---- - - -#### `scrollSensitivity` option -Defines how near the mouse must be to an edge to start scrolling. - - ---- - - -#### `scrollSpeed` option -The speed at which the window should scroll once the mouse pointer gets within the `scrollSensitivity` distance. - - ---- - - - -### Support AngularJS -Include [ng-sortable.js](ng-sortable.js) - -Demo: http://jsbin.com/naduvo/1/edit?html,js,output - -```html -
- - - - - -
-``` - - -```js -angular.module('myApp', ['ng-sortable']) - .controller('demo', ['$scope', function ($scope) { - $scope.items = ['item 1', 'item 2']; - $scope.foo = ['foo 1', '..']; - $scope.bar = ['bar 1', '..']; - $scope.barConfig = { - group: 'foobar', - animation: 150, - onSort: function (/** ngSortEvent */evt){ - // @see https://github.com/RubaXa/Sortable/blob/master/ng-sortable.js#L18-L24 - } - }; - }]); -``` - - ---- - - - -### Support React -Include [react-sortable-mixin.js](react-sortable-mixin.js). -See [more options](react-sortable-mixin.js#L26). - - -```jsx -var SortableList = React.createClass({ - mixins: [SortableMixin], - - getInitialState: function() { - return { - items: ['Mixin', 'Sortable'] - }; - }, - - handleSort: function (/** Event */evt) { /*..*/ }, - - render: function() { - return - } -}); - -React.render(, document.body); - - -// -// Groups -// -var AllUsers = React.createClass({ - mixins: [SortableMixin], - - sortableOptions: { - ref: "user", - group: "shared", - model: "users" - }, - - getInitialState: function() { - return { users: ['Abbi', 'Adela', 'Bud', 'Cate', 'Davis', 'Eric']; }; - }, - - render: function() { - return ( -

Users

- - ); - } -}); - -var ApprovedUsers = React.createClass({ - mixins: [SortableMixin], - sortableOptions: { group: "shared" }, - - getInitialState: function() { - return { items: ['Hal', 'Judy']; }; - }, - - render: function() { - return - } -}); - -React.render(
- -
- -
, document.body); -``` - - ---- - - - -### Support KnockoutJS -Include [knockout-sortable.js](knockout-sortable.js) - -```html -
- -
- -
- -
-``` - -Using this bindingHandler sorts the observableArray when the user sorts the HTMLElements. - -The sortable/draggable bindingHandlers supports the same syntax as Knockouts built in [template](http://knockoutjs.com/documentation/template-binding.html) binding except for the `data` option, meaning that you could supply the name of a template or specify a separate templateEngine. The difference between the sortable and draggable handlers is that the draggable has the sortable `group` option set to `{pull:'clone',put: false}` and the `sort` option set to false by default (overridable). - -Other attributes are: -* options: an object that contains settings for the underlaying sortable, ie `group`,`handle`, events etc. -* collection: if your `foreach` array is a computed then you would supply the underlaying observableArray that you would like to sort here. - - ---- - - -### Method - - -##### option(name:`String`[, value:`*`]):`*` -Get or set the option. - - - -##### closest(el:`String`[, selector:`HTMLElement`]):`HTMLElement|null` -For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - - -##### toArray():`String[]` -Serializes the sortable's item `data-id`'s (`dataIdAttr` option) into an array of string. - - -##### sort(order:`String[]`) -Sorts the elements according to the array. - -```js -var order = sortable.toArray(); -sortable.sort(order.reverse()); // apply -``` - - -##### save() -Save the current sorting (see [store](#store)) - - -##### destroy() -Removes the sortable functionality completely. - - ---- - - - -### Store -Saving and restoring of the sort. - -```html - -``` - -```js -Sortable.create(el, { - group: "localStorage-example", - store: { - /** - * Get the order of elements. Called once during initialization. - * @param {Sortable} sortable - * @returns {Array} - */ - get: function (sortable) { - var order = localStorage.getItem(sortable.options.group); - return order ? order.split('|') : []; - }, - - /** - * Save the order of elements. Called onEnd (when the item is dropped). - * @param {Sortable} sortable - */ - set: function (sortable) { - var order = sortable.toArray(); - localStorage.setItem(sortable.options.group, order.join('|')); - } - } -}) -``` - - ---- - - - -### Bootstrap -Demo: http://jsbin.com/luxero/2/edit?html,js,output - -```html - - - - - - - - - - - - -``` - - ---- - - -### Static methods & properties - - - -##### Sortable.create(el:`HTMLElement`[, options:`Object`]):`Sortable` -Create new instance. - - ---- - - -##### Sortable.active:`Sortable` -Link to the active instance. - - ---- - - -##### Sortable.utils -* on(el`:HTMLElement`, event`:String`, fn`:Function`) — attach an event handler function -* off(el`:HTMLElement`, event`:String`, fn`:Function`) — remove an event handler -* css(el`:HTMLElement`)`:Object` — get the values of all the CSS properties -* css(el`:HTMLElement`, prop`:String`)`:Mixed` — get the value of style properties -* css(el`:HTMLElement`, prop`:String`, value`:String`) — set one CSS properties -* css(el`:HTMLElement`, props`:Object`) — set more CSS properties -* find(ctx`:HTMLElement`, tagName`:String`[, iterator`:Function`])`:Array` — get elements by tag name -* bind(ctx`:Mixed`, fn`:Function`)`:Function` — Takes a function and returns a new one that will always have a particular context -* is(el`:HTMLElement`, selector`:String`)`:Boolean` — check the current matched set of elements against a selector -* closest(el`:HTMLElement`, selector`:String`[, ctx`:HTMLElement`])`:HTMLElement|Null` — for each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree -* toggleClass(el`:HTMLElement`, name`:String`, state`:Boolean`) — add or remove one classes from each element - - ---- - - - -### CDN - -```html - - - - - - - - - - -``` - - ---- - - - -### jQuery compatibility -To assemble plugin for jQuery, perform the following steps: - -```bash - cd Sortable - npm install - grunt jquery -``` - -Now you can use `jquery.fn.sortable.js`:
-(or `jquery.fn.sortable.min.js` if you run `grunt jquery:min`) - -```js - $("#list").sortable({ /* options */ }); // init - - $("#list").sortable("widget"); // get Sortable instance - - $("#list").sortable("destroy"); // destroy Sortable instance - - $("#list").sortable("{method-name}"); // call an instance method - - $("#list").sortable("{method-name}", "foo", "bar"); // call an instance method with parameters -``` - -And `grunt jquery:mySortableFunc` → `jquery.fn.mySortableFunc.js` - ---- - - -### Contributing (Issue/PR) - -Please, [read this](CONTRIBUTING.md). - - ---- - - -## MIT LICENSE -Copyright 2013-2015 Lebedev Konstantin -http://rubaxa.github.io/Sortable/ - -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/Sortable.js b/Sortable.js index 9a24f6e97..07ecc1832 100644 --- a/Sortable.js +++ b/Sortable.js @@ -1,1144 +1,3388 @@ /**! - * Sortable + * Sortable 1.15.6 * @author RubaXa + * @author owenm * @license MIT */ - - -(function (factory) { - "use strict"; - - if (typeof define === "function" && define.amd) { - define(factory); - } - else if (typeof module != "undefined" && typeof module.exports != "undefined") { - module.exports = factory(); - } - else if (typeof Package !== "undefined") { - Sortable = factory(); // export for Meteor.js - } - else { - /* jshint sub:true */ - window["Sortable"] = factory(); - } -})(function () { - "use strict"; - - var dragEl, - ghostEl, - cloneEl, - rootEl, - nextEl, - - scrollEl, - scrollParentEl, - - lastEl, - lastCSS, - - oldIndex, - newIndex, - - activeGroup, - autoScroll = {}, - - tapEvt, - touchEvt, - - /** @const */ - RSPACE = /\s+/g, - - expando = 'Sortable' + (new Date).getTime(), - - win = window, - document = win.document, - parseInt = win.parseInt, - - supportDraggable = !!('draggable' in document.createElement('div')), - - _silent = false, - - abs = Math.abs, - slice = [].slice, - - touchDragOverListeners = [], - - _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl) { - // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521 - if (rootEl && options.scroll) { - var el, - rect, - sens = options.scrollSensitivity, - speed = options.scrollSpeed, - - x = evt.clientX, - y = evt.clientY, - - winWidth = window.innerWidth, - winHeight = window.innerHeight, - - vx, - vy - ; - - // Delect scrollEl - if (scrollParentEl !== rootEl) { - scrollEl = options.scroll; - scrollParentEl = rootEl; - - if (scrollEl === true) { - scrollEl = rootEl; - - do { - if ((scrollEl.offsetWidth < scrollEl.scrollWidth) || - (scrollEl.offsetHeight < scrollEl.scrollHeight) - ) { - break; - } - /* jshint boss:true */ - } while (scrollEl = scrollEl.parentNode); - } - } - - if (scrollEl) { - el = scrollEl; - rect = scrollEl.getBoundingClientRect(); - vx = (abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens); - vy = (abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens); - } - - - if (!(vx || vy)) { - vx = (winWidth - x <= sens) - (x <= sens); - vy = (winHeight - y <= sens) - (y <= sens); - - /* jshint expr:true */ - (vx || vy) && (el = win); - } - - - if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) { - autoScroll.el = el; - autoScroll.vx = vx; - autoScroll.vy = vy; - - clearInterval(autoScroll.pid); - - if (el) { - autoScroll.pid = setInterval(function () { - if (el === win) { - win.scrollTo(win.pageXOffset + vx * speed, win.pageYOffset + vy * speed); - } else { - vy && (el.scrollTop += vy * speed); - vx && (el.scrollLeft += vx * speed); - } - }, 24); - } - } - } - }, 30) - ; - - - - /** - * @class Sortable - * @param {HTMLElement} el - * @param {Object} [options] - */ - function Sortable(el, options) { - this.el = el; // root element - this.options = options = _extend({}, options); - - - // Export instance - el[expando] = this; - - - // Default options - var defaults = { - group: Math.random(), - sort: true, - disabled: false, - store: null, - handle: null, - scroll: true, - scrollSensitivity: 30, - scrollSpeed: 10, - draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*', - ghostClass: 'sortable-ghost', - ignore: 'a, img', - filter: null, - animation: 0, - setData: function (dataTransfer, dragEl) { - dataTransfer.setData('Text', dragEl.textContent); - }, - dropBubble: false, - dragoverBubble: false, - dataIdAttr: 'data-id', - delay: 0 - }; - - - // Set default options - for (var name in defaults) { - !(name in options) && (options[name] = defaults[name]); - } - - - var group = options.group; - - if (!group || typeof group != 'object') { - group = options.group = { name: group }; - } - - - ['pull', 'put'].forEach(function (key) { - if (!(key in group)) { - group[key] = true; - } - }); - - - options.groups = ' ' + group.name + (group.put.join ? ' ' + group.put.join(' ') : '') + ' '; - - - // Bind all private methods - for (var fn in this) { - if (fn.charAt(0) === '_') { - this[fn] = _bind(this, this[fn]); - } - } - - - // Bind events - _on(el, 'mousedown', this._onTapStart); - _on(el, 'touchstart', this._onTapStart); - - _on(el, 'dragover', this); - _on(el, 'dragenter', this); - - touchDragOverListeners.push(this._onDragOver); - - // Restore sorting - options.store && this.sort(options.store.get(this)); - } - - - Sortable.prototype = /** @lends Sortable.prototype */ { - constructor: Sortable, - - _onTapStart: function (/** Event|TouchEvent */evt) { - var _this = this, - el = this.el, - options = this.options, - type = evt.type, - touch = evt.touches && evt.touches[0], - target = (touch || evt).target, - originalTarget = target, - filter = options.filter; - - - if (type === 'mousedown' && evt.button !== 0 || options.disabled) { - return; // only left button or enabled - } - - target = _closest(target, options.draggable, el); - - if (!target) { - return; - } - - // get the index of the dragged element within its parent - oldIndex = _index(target); - - // Check filter - if (typeof filter === 'function') { - if (filter.call(this, evt, target, this)) { - _dispatchEvent(_this, originalTarget, 'filter', target, el, oldIndex); - evt.preventDefault(); - return; // cancel dnd - } - } - else if (filter) { - filter = filter.split(',').some(function (criteria) { - criteria = _closest(originalTarget, criteria.trim(), el); - - if (criteria) { - _dispatchEvent(_this, criteria, 'filter', target, el, oldIndex); - return true; - } - }); - - if (filter) { - evt.preventDefault(); - return; // cancel dnd - } - } - - - if (options.handle && !_closest(originalTarget, options.handle, el)) { - return; - } - - - // Prepare `dragstart` - this._prepareDragStart(evt, touch, target); - }, - - _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target) { - var _this = this, - el = _this.el, - options = _this.options, - ownerDocument = el.ownerDocument, - dragStartFn; - - if (target && !dragEl && (target.parentNode === el)) { - tapEvt = evt; - - rootEl = el; - dragEl = target; - nextEl = dragEl.nextSibling; - activeGroup = options.group; - - dragStartFn = function () { - // Delayed drag has been triggered - // we can re-enable the events: touchmove/mousemove - _this._disableDelayedDrag(); - - // Make the element draggable - dragEl.draggable = true; - - // Disable "draggable" - options.ignore.split(',').forEach(function (criteria) { - _find(dragEl, criteria.trim(), _disableDraggable); - }); - - // Bind the events: dragstart/dragend - _this._triggerDragStart(touch); - }; - - _on(ownerDocument, 'mouseup', _this._onDrop); - _on(ownerDocument, 'touchend', _this._onDrop); - _on(ownerDocument, 'touchcancel', _this._onDrop); - - if (options.delay) { - // If the user moves the pointer before the delay has been reached: - // disable the delayed drag - _on(ownerDocument, 'mousemove', _this._disableDelayedDrag); - _on(ownerDocument, 'touchmove', _this._disableDelayedDrag); - - _this._dragStartTimer = setTimeout(dragStartFn, options.delay); - } else { - dragStartFn(); - } - } - }, - - _disableDelayedDrag: function () { - var ownerDocument = this.el.ownerDocument; - - clearTimeout(this._dragStartTimer); - - _off(ownerDocument, 'mousemove', this._disableDelayedDrag); - _off(ownerDocument, 'touchmove', this._disableDelayedDrag); - }, - - _triggerDragStart: function (/** Touch */touch) { - if (touch) { - // Touch device support - tapEvt = { - target: dragEl, - clientX: touch.clientX, - clientY: touch.clientY - }; - - this._onDragStart(tapEvt, 'touch'); - } - else if (!supportDraggable) { - this._onDragStart(tapEvt, true); - } - else { - _on(dragEl, 'dragend', this); - _on(rootEl, 'dragstart', this._onDragStart); - } - - try { - if (document.selection) { - document.selection.empty(); - } else { - window.getSelection().removeAllRanges(); - } - } catch (err) { - } - }, - - _dragStarted: function () { - if (rootEl && dragEl) { - // Apply effect - _toggleClass(dragEl, this.options.ghostClass, true); - - Sortable.active = this; - - // Drag start event - _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, oldIndex); - } - }, - - _emulateDragOver: function () { - if (touchEvt) { - _css(ghostEl, 'display', 'none'); - - var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY), - parent = target, - groupName = ' ' + this.options.group.name + '', - i = touchDragOverListeners.length; - - if (parent) { - do { - if (parent[expando] && parent[expando].options.groups.indexOf(groupName) > -1) { - while (i--) { - touchDragOverListeners[i]({ - clientX: touchEvt.clientX, - clientY: touchEvt.clientY, - target: target, - rootEl: parent - }); - } - - break; - } - - target = parent; // store last element - } - /* jshint boss:true */ - while (parent = parent.parentNode); - } - - _css(ghostEl, 'display', ''); - } - }, - - - _onTouchMove: function (/**TouchEvent*/evt) { - if (tapEvt) { - var touch = evt.touches ? evt.touches[0] : evt, - dx = touch.clientX - tapEvt.clientX, - dy = touch.clientY - tapEvt.clientY, - translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)'; - - touchEvt = touch; - - _css(ghostEl, 'webkitTransform', translate3d); - _css(ghostEl, 'mozTransform', translate3d); - _css(ghostEl, 'msTransform', translate3d); - _css(ghostEl, 'transform', translate3d); - - evt.preventDefault(); - } - }, - - - _onDragStart: function (/**Event*/evt, /**boolean*/useFallback) { - var dataTransfer = evt.dataTransfer, - options = this.options; - - this._offUpEvents(); - - if (activeGroup.pull == 'clone') { - cloneEl = dragEl.cloneNode(true); - _css(cloneEl, 'display', 'none'); - rootEl.insertBefore(cloneEl, dragEl); - } - - if (useFallback) { - var rect = dragEl.getBoundingClientRect(), - css = _css(dragEl), - ghostRect; - - ghostEl = dragEl.cloneNode(true); - - _css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10)); - _css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10)); - _css(ghostEl, 'width', rect.width); - _css(ghostEl, 'height', rect.height); - _css(ghostEl, 'opacity', '0.8'); - _css(ghostEl, 'position', 'fixed'); - _css(ghostEl, 'zIndex', '100000'); - - rootEl.appendChild(ghostEl); - - // Fixing dimensions. - ghostRect = ghostEl.getBoundingClientRect(); - _css(ghostEl, 'width', rect.width * 2 - ghostRect.width); - _css(ghostEl, 'height', rect.height * 2 - ghostRect.height); - - if (useFallback === 'touch') { - // Bind touch events - _on(document, 'touchmove', this._onTouchMove); - _on(document, 'touchend', this._onDrop); - _on(document, 'touchcancel', this._onDrop); - } else { - // Old brwoser - _on(document, 'mousemove', this._onTouchMove); - _on(document, 'mouseup', this._onDrop); - } - - this._loopId = setInterval(this._emulateDragOver, 150); - } - else { - if (dataTransfer) { - dataTransfer.effectAllowed = 'move'; - options.setData && options.setData.call(this, dataTransfer, dragEl); - } - - _on(document, 'drop', this); - } - - setTimeout(this._dragStarted, 0); - }, - - _onDragOver: function (/**Event*/evt) { - var el = this.el, - target, - dragRect, - revert, - options = this.options, - group = options.group, - groupPut = group.put, - isOwner = (activeGroup === group), - canSort = options.sort; - - if (evt.preventDefault !== void 0) { - evt.preventDefault(); - !options.dragoverBubble && evt.stopPropagation(); - } - - if (activeGroup && !options.disabled && - (isOwner - ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list - : activeGroup.pull && groupPut && ( - (activeGroup.name === group.name) || // by Name - (groupPut.indexOf && ~groupPut.indexOf(activeGroup.name)) // by Array - ) - ) && - (evt.rootEl === void 0 || evt.rootEl === this.el) // touch fallback - ) { - // Smart auto-scrolling - _autoScroll(evt, options, this.el); - - if (_silent) { - return; - } - - target = _closest(evt.target, options.draggable, el); - dragRect = dragEl.getBoundingClientRect(); - - - if (revert) { - _cloneHide(true); - - if (cloneEl || nextEl) { - rootEl.insertBefore(dragEl, cloneEl || nextEl); - } - else if (!canSort) { - rootEl.appendChild(dragEl); - } - - return; - } - - - if ((el.children.length === 0) || (el.children[0] === ghostEl) || - (el === evt.target) && (target = _ghostInBottom(el, evt)) - ) { - if (target) { - if (target.animated) { - return; - } - targetRect = target.getBoundingClientRect(); - } - - _cloneHide(isOwner); - - if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect) !== false) { - el.appendChild(dragEl); - this._animate(dragRect, dragEl); - target && this._animate(targetRect, target); - } - } - else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) { - if (lastEl !== target) { - lastEl = target; - lastCSS = _css(target); - } - - - var targetRect = target.getBoundingClientRect(), - width = targetRect.right - targetRect.left, - height = targetRect.bottom - targetRect.top, - floating = /left|right|inline/.test(lastCSS.cssFloat + lastCSS.display), - isWide = (target.offsetWidth > dragEl.offsetWidth), - isLong = (target.offsetHeight > dragEl.offsetHeight), - halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5, - nextSibling = target.nextElementSibling, - moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect), - after - ; - - if (moveVector !== false) { - _silent = true; - setTimeout(_unsilent, 30); - - _cloneHide(isOwner); - - if (moveVector === 1 || moveVector === -1) { - after = (moveVector === 1); - } - else if (floating) { - after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide; - } else { - after = (nextSibling !== dragEl) && !isLong || halfway && isLong; - } - - if (after && !nextSibling) { - el.appendChild(dragEl); - } else { - target.parentNode.insertBefore(dragEl, after ? nextSibling : target); - } - - this._animate(dragRect, dragEl); - this._animate(targetRect, target); - } - } - } - }, - - _animate: function (prevRect, target) { - var ms = this.options.animation; - - if (ms) { - var currentRect = target.getBoundingClientRect(); - - _css(target, 'transition', 'none'); - _css(target, 'transform', 'translate3d(' - + (prevRect.left - currentRect.left) + 'px,' - + (prevRect.top - currentRect.top) + 'px,0)' - ); - - target.offsetWidth; // repaint - - _css(target, 'transition', 'all ' + ms + 'ms'); - _css(target, 'transform', 'translate3d(0,0,0)'); - - clearTimeout(target.animated); - target.animated = setTimeout(function () { - _css(target, 'transition', ''); - _css(target, 'transform', ''); - target.animated = false; - }, ms); - } - }, - - _offUpEvents: function () { - var ownerDocument = this.el.ownerDocument; - - _off(document, 'touchmove', this._onTouchMove); - _off(ownerDocument, 'mouseup', this._onDrop); - _off(ownerDocument, 'touchend', this._onDrop); - _off(ownerDocument, 'touchcancel', this._onDrop); - }, - - _onDrop: function (/**Event*/evt) { - var el = this.el, - options = this.options; - - clearInterval(this._loopId); - clearInterval(autoScroll.pid); - clearTimeout(this._dragStartTimer); - - // Unbind events - _off(document, 'drop', this); - _off(document, 'mousemove', this._onTouchMove); - _off(el, 'dragstart', this._onDragStart); - - this._offUpEvents(); - - if (evt) { - evt.preventDefault(); - !options.dropBubble && evt.stopPropagation(); - - ghostEl && ghostEl.parentNode.removeChild(ghostEl); - - if (dragEl) { - _off(dragEl, 'dragend', this); - - _disableDraggable(dragEl); - _toggleClass(dragEl, this.options.ghostClass, false); - - if (rootEl !== dragEl.parentNode) { - newIndex = _index(dragEl); - - // drag from one list and drop into another - _dispatchEvent(null, dragEl.parentNode, 'sort', dragEl, rootEl, oldIndex, newIndex); - _dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex); - - // Add event - _dispatchEvent(null, dragEl.parentNode, 'add', dragEl, rootEl, oldIndex, newIndex); - - // Remove event - _dispatchEvent(this, rootEl, 'remove', dragEl, rootEl, oldIndex, newIndex); - } - else { - // Remove clone - cloneEl && cloneEl.parentNode.removeChild(cloneEl); - - if (dragEl.nextSibling !== nextEl) { - // Get the index of the dragged element within its parent - newIndex = _index(dragEl); - - // drag & drop within the same list - _dispatchEvent(this, rootEl, 'update', dragEl, rootEl, oldIndex, newIndex); - _dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex); - } - } - - if (Sortable.active) { - // Drag end event - _dispatchEvent(this, rootEl, 'end', dragEl, rootEl, oldIndex, newIndex); - - // Save sorting - this.save(); - } - } - - // Nulling - rootEl = - dragEl = - ghostEl = - nextEl = - cloneEl = - - scrollEl = - scrollParentEl = - - tapEvt = - touchEvt = - - lastEl = - lastCSS = - - activeGroup = - Sortable.active = null; - } - }, - - - handleEvent: function (/**Event*/evt) { - var type = evt.type; - - if (type === 'dragover' || type === 'dragenter') { - if (dragEl) { - this._onDragOver(evt); - _globalDragOver(evt); - } - } - else if (type === 'drop' || type === 'dragend') { - this._onDrop(evt); - } - }, - - - /** - * Serializes the item into an array of string. - * @returns {String[]} - */ - toArray: function () { - var order = [], - el, - children = this.el.children, - i = 0, - n = children.length, - options = this.options; - - for (; i < n; i++) { - el = children[i]; - if (_closest(el, options.draggable, this.el)) { - order.push(el.getAttribute(options.dataIdAttr) || _generateId(el)); - } - } - - return order; - }, - - - /** - * Sorts the elements according to the array. - * @param {String[]} order order of the items - */ - sort: function (order) { - var items = {}, rootEl = this.el; - - this.toArray().forEach(function (id, i) { - var el = rootEl.children[i]; - - if (_closest(el, this.options.draggable, rootEl)) { - items[id] = el; - } - }, this); - - order.forEach(function (id) { - if (items[id]) { - rootEl.removeChild(items[id]); - rootEl.appendChild(items[id]); - } - }); - }, - - - /** - * Save the current sorting - */ - save: function () { - var store = this.options.store; - store && store.set(this); - }, - - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * @param {HTMLElement} el - * @param {String} [selector] default: `options.draggable` - * @returns {HTMLElement|null} - */ - closest: function (el, selector) { - return _closest(el, selector || this.options.draggable, this.el); - }, - - - /** - * Set/get option - * @param {string} name - * @param {*} [value] - * @returns {*} - */ - option: function (name, value) { - var options = this.options; - - if (value === void 0) { - return options[name]; - } else { - options[name] = value; - } - }, - - - /** - * Destroy - */ - destroy: function () { - var el = this.el; - - el[expando] = null; - - _off(el, 'mousedown', this._onTapStart); - _off(el, 'touchstart', this._onTapStart); - - _off(el, 'dragover', this); - _off(el, 'dragenter', this); - - // Remove draggable attributes - Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) { - el.removeAttribute('draggable'); - }); - - touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1); - - this._onDrop(); - - this.el = el = null; - } - }; - - - function _cloneHide(state) { - if (cloneEl && (cloneEl.state !== state)) { - _css(cloneEl, 'display', state ? 'none' : ''); - !state && cloneEl.state && rootEl.insertBefore(cloneEl, dragEl); - cloneEl.state = state; - } - } - - - function _bind(ctx, fn) { - var args = slice.call(arguments, 2); - return fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function () { - return fn.apply(ctx, args.concat(slice.call(arguments))); - }; - } - - - function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) { - if (el) { - ctx = ctx || document; - selector = selector.split('.'); - - var tag = selector.shift().toUpperCase(), - re = new RegExp('\\s(' + selector.join('|') + ')(?=\\s)', 'g'); - - do { - if ( - (tag === '>*' && el.parentNode === ctx) || ( - (tag === '' || el.nodeName.toUpperCase() == tag) && - (!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length) - ) - ) { - return el; - } - } - while (el !== ctx && (el = el.parentNode)); - } - - return null; - } - - - function _globalDragOver(/**Event*/evt) { - evt.dataTransfer.dropEffect = 'move'; - evt.preventDefault(); - } - - - function _on(el, event, fn) { - el.addEventListener(event, fn, false); - } - - - function _off(el, event, fn) { - el.removeEventListener(event, fn, false); - } - - - function _toggleClass(el, name, state) { - if (el) { - if (el.classList) { - el.classList[state ? 'add' : 'remove'](name); - } - else { - var className = (' ' + el.className + ' ').replace(RSPACE, ' ').replace(' ' + name + ' ', ' '); - el.className = (className + (state ? ' ' + name : '')).replace(RSPACE, ' '); - } - } - } - - - function _css(el, prop, val) { - var style = el && el.style; - - if (style) { - if (val === void 0) { - if (document.defaultView && document.defaultView.getComputedStyle) { - val = document.defaultView.getComputedStyle(el, ''); - } - else if (el.currentStyle) { - val = el.currentStyle; - } - - return prop === void 0 ? val : val[prop]; - } - else { - if (!(prop in style)) { - prop = '-webkit-' + prop; - } - - style[prop] = val + (typeof val === 'string' ? '' : 'px'); - } - } - } - - - function _find(ctx, tagName, iterator) { - if (ctx) { - var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length; - - if (iterator) { - for (; i < n; i++) { - iterator(list[i], i); - } - } - - return list; - } - - return []; - } - - - - function _dispatchEvent(sortable, rootEl, name, targetEl, fromEl, startIndex, newIndex) { - var evt = document.createEvent('Event'), - options = (sortable || rootEl[expando]).options, - onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); - - evt.initEvent(name, true, true); - - evt.to = rootEl; - evt.from = fromEl || rootEl; - evt.item = targetEl || rootEl; - evt.clone = cloneEl; - - evt.oldIndex = startIndex; - evt.newIndex = newIndex; - - rootEl.dispatchEvent(evt); - - if (options[onName]) { - options[onName].call(sortable, evt); - } - } - - - function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect) { - var evt, - sortable = fromEl[expando], - onMoveFn = sortable.options.onMove, - retVal; - - if (onMoveFn) { - evt = document.createEvent('Event'); - evt.initEvent('move', true, true); - - evt.to = toEl; - evt.from = fromEl; - evt.dragged = dragEl; - evt.draggedRect = dragRect; - evt.related = targetEl || toEl; - evt.relatedRect = targetRect || toEl.getBoundingClientRect(); - - retVal = onMoveFn.call(sortable, evt); - } - - return retVal; - } - - - function _disableDraggable(el) { - el.draggable = false; - } - - - function _unsilent() { - _silent = false; - } - - - /** @returns {HTMLElement|false} */ - function _ghostInBottom(el, evt) { - var lastEl = el.lastElementChild, - rect = lastEl.getBoundingClientRect(); - - return (evt.clientY - (rect.top + rect.height) > 5) && lastEl; // min delta - } - - - /** - * Generate id - * @param {HTMLElement} el - * @returns {String} - * @private - */ - function _generateId(el) { - var str = el.tagName + el.className + el.src + el.href + el.textContent, - i = str.length, - sum = 0; - - while (i--) { - sum += str.charCodeAt(i); - } - - return sum.toString(36); - } - - /** - * Returns the index of an element within its parent - * @param el - * @returns {number} - * @private - */ - function _index(/**HTMLElement*/el) { - var index = 0; - while (el && (el = el.previousElementSibling)) { - if (el.nodeName.toUpperCase() !== 'TEMPLATE') { - index++; - } - } - return index; - } - - function _throttle(callback, ms) { - var args, _this; - - return function () { - if (args === void 0) { - args = arguments; - _this = this; - - setTimeout(function () { - if (args.length === 1) { - callback.call(_this, args[0]); - } else { - callback.apply(_this, args); - } - - args = void 0; - }, ms); - } - }; - } - - function _extend(dst, src) { - if (dst && src) { - for (var key in src) { - if (src.hasOwnProperty(key)) { - dst[key] = src[key]; - } - } - } - - return dst; - } - - - // Export utils - Sortable.utils = { - on: _on, - off: _off, - css: _css, - find: _find, - bind: _bind, - is: function (el, selector) { - return !!_closest(el, selector, el); - }, - extend: _extend, - throttle: _throttle, - closest: _closest, - toggleClass: _toggleClass, - index: _index - }; - - - Sortable.version = '1.2.1'; - - - /** - * Create sortable instance - * @param {HTMLElement} el - * @param {Object} [options] - */ - Sortable.create = function (el, options) { - return new Sortable(el, options); - }; - - // Export - return Sortable; -}); +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.Sortable = factory()); +}(this, (function () { 'use strict'; + + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + return target; + } + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + return _typeof(obj); + } + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends.apply(this, arguments); + } + function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + return target; + } + function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = _objectWithoutPropertiesLoose(source, excluded); + var key, i; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + return target; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + } + 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; + } + 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 version = "1.15.6"; + + function userAgent(pattern) { + if (typeof window !== 'undefined' && window.navigator) { + return !! /*@__PURE__*/navigator.userAgent.match(pattern); + } + } + var IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i); + var Edge = userAgent(/Edge/i); + var FireFox = userAgent(/firefox/i); + var Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i); + var IOS = userAgent(/iP(ad|od|hone)/i); + var ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i); + + var captureMode = { + capture: false, + passive: false + }; + function on(el, event, fn) { + el.addEventListener(event, fn, !IE11OrLess && captureMode); + } + function off(el, event, fn) { + el.removeEventListener(event, fn, !IE11OrLess && captureMode); + } + function matches( /**HTMLElement*/el, /**String*/selector) { + if (!selector) return; + selector[0] === '>' && (selector = selector.substring(1)); + if (el) { + try { + if (el.matches) { + return el.matches(selector); + } else if (el.msMatchesSelector) { + return el.msMatchesSelector(selector); + } else if (el.webkitMatchesSelector) { + return el.webkitMatchesSelector(selector); + } + } catch (_) { + return false; + } + } + return false; + } + function getParentOrHost(el) { + return el.host && el !== document && el.host.nodeType ? el.host : el.parentNode; + } + function closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) { + if (el) { + ctx = ctx || document; + do { + if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) { + return el; + } + if (el === ctx) break; + /* jshint boss:true */ + } while (el = getParentOrHost(el)); + } + return null; + } + var R_SPACE = /\s+/g; + function toggleClass(el, name, state) { + if (el && name) { + if (el.classList) { + el.classList[state ? 'add' : 'remove'](name); + } else { + var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' '); + el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' '); + } + } + } + function css(el, prop, val) { + var style = el && el.style; + if (style) { + if (val === void 0) { + if (document.defaultView && document.defaultView.getComputedStyle) { + val = document.defaultView.getComputedStyle(el, ''); + } else if (el.currentStyle) { + val = el.currentStyle; + } + return prop === void 0 ? val : val[prop]; + } else { + if (!(prop in style) && prop.indexOf('webkit') === -1) { + prop = '-webkit-' + prop; + } + style[prop] = val + (typeof val === 'string' ? '' : 'px'); + } + } + } + function matrix(el, selfOnly) { + var appliedTransforms = ''; + if (typeof el === 'string') { + appliedTransforms = el; + } else { + do { + var transform = css(el, 'transform'); + if (transform && transform !== 'none') { + appliedTransforms = transform + ' ' + appliedTransforms; + } + /* jshint boss:true */ + } while (!selfOnly && (el = el.parentNode)); + } + var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix; + /*jshint -W056 */ + return matrixFn && new matrixFn(appliedTransforms); + } + function find(ctx, tagName, iterator) { + if (ctx) { + var list = ctx.getElementsByTagName(tagName), + i = 0, + n = list.length; + if (iterator) { + for (; i < n; i++) { + iterator(list[i], i); + } + } + return list; + } + return []; + } + function getWindowScrollingElement() { + var scrollingElement = document.scrollingElement; + if (scrollingElement) { + return scrollingElement; + } else { + return document.documentElement; + } + } + + /** + * Returns the "bounding client rect" of given element + * @param {HTMLElement} el The element whose boundingClientRect is wanted + * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container + * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr + * @param {[Boolean]} undoScale Whether the container's scale() should be undone + * @param {[HTMLElement]} container The parent the element will be placed in + * @return {Object} The boundingClientRect of el, with specified adjustments + */ + function getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) { + if (!el.getBoundingClientRect && el !== window) return; + var elRect, top, left, bottom, right, height, width; + if (el !== window && el.parentNode && el !== getWindowScrollingElement()) { + elRect = el.getBoundingClientRect(); + top = elRect.top; + left = elRect.left; + bottom = elRect.bottom; + right = elRect.right; + height = elRect.height; + width = elRect.width; + } else { + top = 0; + left = 0; + bottom = window.innerHeight; + right = window.innerWidth; + height = window.innerHeight; + width = window.innerWidth; + } + if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) { + // Adjust for translate() + container = container || el.parentNode; + + // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312) + // Not needed on <= IE11 + if (!IE11OrLess) { + do { + if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) { + var containerRect = container.getBoundingClientRect(); + + // Set relative to edges of padding box of container + top -= containerRect.top + parseInt(css(container, 'border-top-width')); + left -= containerRect.left + parseInt(css(container, 'border-left-width')); + bottom = top + elRect.height; + right = left + elRect.width; + break; + } + /* jshint boss:true */ + } while (container = container.parentNode); + } + } + if (undoScale && el !== window) { + // Adjust for scale() + var elMatrix = matrix(container || el), + scaleX = elMatrix && elMatrix.a, + scaleY = elMatrix && elMatrix.d; + if (elMatrix) { + top /= scaleY; + left /= scaleX; + width /= scaleX; + height /= scaleY; + bottom = top + height; + right = left + width; + } + } + return { + top: top, + left: left, + bottom: bottom, + right: right, + width: width, + height: height + }; + } + + /** + * Checks if a side of an element is scrolled past a side of its parents + * @param {HTMLElement} el The element who's side being scrolled out of view is in question + * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom') + * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom') + * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element + */ + function isScrolledPast(el, elSide, parentSide) { + var parent = getParentAutoScrollElement(el, true), + elSideVal = getRect(el)[elSide]; + + /* jshint boss:true */ + while (parent) { + var parentSideVal = getRect(parent)[parentSide], + visible = void 0; + if (parentSide === 'top' || parentSide === 'left') { + visible = elSideVal >= parentSideVal; + } else { + visible = elSideVal <= parentSideVal; + } + if (!visible) return parent; + if (parent === getWindowScrollingElement()) break; + parent = getParentAutoScrollElement(parent, false); + } + return false; + } + + /** + * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible) + * and non-draggable elements + * @param {HTMLElement} el The parent element + * @param {Number} childNum The index of the child + * @param {Object} options Parent Sortable's options + * @return {HTMLElement} The child at index childNum, or null if not found + */ + function getChild(el, childNum, options, includeDragEl) { + var currentChild = 0, + i = 0, + children = el.children; + while (i < children.length) { + if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) { + if (currentChild === childNum) { + return children[i]; + } + currentChild++; + } + i++; + } + return null; + } + + /** + * Gets the last child in the el, ignoring ghostEl or invisible elements (clones) + * @param {HTMLElement} el Parent element + * @param {selector} selector Any other elements that should be ignored + * @return {HTMLElement} The last child, ignoring ghostEl + */ + function lastChild(el, selector) { + var last = el.lastElementChild; + while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) { + last = last.previousElementSibling; + } + return last || null; + } + + /** + * Returns the index of an element within its parent for a selected set of + * elements + * @param {HTMLElement} el + * @param {selector} selector + * @return {number} + */ + function index(el, selector) { + var index = 0; + if (!el || !el.parentNode) { + return -1; + } + + /* jshint boss:true */ + while (el = el.previousElementSibling) { + if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) { + index++; + } + } + return index; + } + + /** + * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements. + * The value is returned in real pixels. + * @param {HTMLElement} el + * @return {Array} Offsets in the format of [left, top] + */ + function getRelativeScrollOffset(el) { + var offsetLeft = 0, + offsetTop = 0, + winScroller = getWindowScrollingElement(); + if (el) { + do { + var elMatrix = matrix(el), + scaleX = elMatrix.a, + scaleY = elMatrix.d; + offsetLeft += el.scrollLeft * scaleX; + offsetTop += el.scrollTop * scaleY; + } while (el !== winScroller && (el = el.parentNode)); + } + return [offsetLeft, offsetTop]; + } + + /** + * Returns the index of the object within the given array + * @param {Array} arr Array that may or may not hold the object + * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find + * @return {Number} The index of the object in the array, or -1 + */ + function indexOfObject(arr, obj) { + for (var i in arr) { + if (!arr.hasOwnProperty(i)) continue; + for (var key in obj) { + if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i); + } + } + return -1; + } + function getParentAutoScrollElement(el, includeSelf) { + // skip to window + if (!el || !el.getBoundingClientRect) return getWindowScrollingElement(); + var elem = el; + var gotSelf = false; + do { + // we don't need to get elem css if it isn't even overflowing in the first place (performance) + if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) { + var elemCSS = css(elem); + if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) { + if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement(); + if (gotSelf || includeSelf) return elem; + gotSelf = true; + } + } + /* jshint boss:true */ + } while (elem = elem.parentNode); + return getWindowScrollingElement(); + } + function extend(dst, src) { + if (dst && src) { + for (var key in src) { + if (src.hasOwnProperty(key)) { + dst[key] = src[key]; + } + } + } + return dst; + } + function isRectEqual(rect1, rect2) { + return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width); + } + var _throttleTimeout; + function throttle(callback, ms) { + return function () { + if (!_throttleTimeout) { + var args = arguments, + _this = this; + if (args.length === 1) { + callback.call(_this, args[0]); + } else { + callback.apply(_this, args); + } + _throttleTimeout = setTimeout(function () { + _throttleTimeout = void 0; + }, ms); + } + }; + } + function cancelThrottle() { + clearTimeout(_throttleTimeout); + _throttleTimeout = void 0; + } + function scrollBy(el, x, y) { + el.scrollLeft += x; + el.scrollTop += y; + } + function clone(el) { + var Polymer = window.Polymer; + var $ = window.jQuery || window.Zepto; + if (Polymer && Polymer.dom) { + return Polymer.dom(el).cloneNode(true); + } else if ($) { + return $(el).clone(true)[0]; + } else { + return el.cloneNode(true); + } + } + function setRect(el, rect) { + css(el, 'position', 'absolute'); + css(el, 'top', rect.top); + css(el, 'left', rect.left); + css(el, 'width', rect.width); + css(el, 'height', rect.height); + } + function unsetRect(el) { + css(el, 'position', ''); + css(el, 'top', ''); + css(el, 'left', ''); + css(el, 'width', ''); + css(el, 'height', ''); + } + function getChildContainingRectFromElement(container, options, ghostEl) { + var rect = {}; + Array.from(container.children).forEach(function (child) { + var _rect$left, _rect$top, _rect$right, _rect$bottom; + if (!closest(child, options.draggable, container, false) || child.animated || child === ghostEl) return; + var childRect = getRect(child); + rect.left = Math.min((_rect$left = rect.left) !== null && _rect$left !== void 0 ? _rect$left : Infinity, childRect.left); + rect.top = Math.min((_rect$top = rect.top) !== null && _rect$top !== void 0 ? _rect$top : Infinity, childRect.top); + rect.right = Math.max((_rect$right = rect.right) !== null && _rect$right !== void 0 ? _rect$right : -Infinity, childRect.right); + rect.bottom = Math.max((_rect$bottom = rect.bottom) !== null && _rect$bottom !== void 0 ? _rect$bottom : -Infinity, childRect.bottom); + }); + rect.width = rect.right - rect.left; + rect.height = rect.bottom - rect.top; + rect.x = rect.left; + rect.y = rect.top; + return rect; + } + var expando = 'Sortable' + new Date().getTime(); + + function AnimationStateManager() { + var animationStates = [], + animationCallbackId; + return { + captureAnimationState: function captureAnimationState() { + animationStates = []; + if (!this.options.animation) return; + var children = [].slice.call(this.el.children); + children.forEach(function (child) { + if (css(child, 'display') === 'none' || child === Sortable.ghost) return; + animationStates.push({ + target: child, + rect: getRect(child) + }); + var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect); + + // If animating: compensate for current animation + if (child.thisAnimationDuration) { + var childMatrix = matrix(child, true); + if (childMatrix) { + fromRect.top -= childMatrix.f; + fromRect.left -= childMatrix.e; + } + } + child.fromRect = fromRect; + }); + }, + addAnimationState: function addAnimationState(state) { + animationStates.push(state); + }, + removeAnimationState: function removeAnimationState(target) { + animationStates.splice(indexOfObject(animationStates, { + target: target + }), 1); + }, + animateAll: function animateAll(callback) { + var _this = this; + if (!this.options.animation) { + clearTimeout(animationCallbackId); + if (typeof callback === 'function') callback(); + return; + } + var animating = false, + animationTime = 0; + animationStates.forEach(function (state) { + var time = 0, + target = state.target, + fromRect = target.fromRect, + toRect = getRect(target), + prevFromRect = target.prevFromRect, + prevToRect = target.prevToRect, + animatingRect = state.rect, + targetMatrix = matrix(target, true); + if (targetMatrix) { + // Compensate for current animation + toRect.top -= targetMatrix.f; + toRect.left -= targetMatrix.e; + } + target.toRect = toRect; + if (target.thisAnimationDuration) { + // Could also check if animatingRect is between fromRect and toRect + if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) && + // Make sure animatingRect is on line between toRect & fromRect + (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) { + // If returning to same place as started from animation and on same axis + time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options); + } + } + + // if fromRect != toRect: animate + if (!isRectEqual(toRect, fromRect)) { + target.prevFromRect = fromRect; + target.prevToRect = toRect; + if (!time) { + time = _this.options.animation; + } + _this.animate(target, animatingRect, toRect, time); + } + if (time) { + animating = true; + animationTime = Math.max(animationTime, time); + clearTimeout(target.animationResetTimer); + target.animationResetTimer = setTimeout(function () { + target.animationTime = 0; + target.prevFromRect = null; + target.fromRect = null; + target.prevToRect = null; + target.thisAnimationDuration = null; + }, time); + target.thisAnimationDuration = time; + } + }); + clearTimeout(animationCallbackId); + if (!animating) { + if (typeof callback === 'function') callback(); + } else { + animationCallbackId = setTimeout(function () { + if (typeof callback === 'function') callback(); + }, animationTime); + } + animationStates = []; + }, + animate: function animate(target, currentRect, toRect, duration) { + if (duration) { + css(target, 'transition', ''); + css(target, 'transform', ''); + var elMatrix = matrix(this.el), + scaleX = elMatrix && elMatrix.a, + scaleY = elMatrix && elMatrix.d, + translateX = (currentRect.left - toRect.left) / (scaleX || 1), + translateY = (currentRect.top - toRect.top) / (scaleY || 1); + target.animatingX = !!translateX; + target.animatingY = !!translateY; + css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)'); + this.forRepaintDummy = repaint(target); // repaint + + css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : '')); + css(target, 'transform', 'translate3d(0,0,0)'); + typeof target.animated === 'number' && clearTimeout(target.animated); + target.animated = setTimeout(function () { + css(target, 'transition', ''); + css(target, 'transform', ''); + target.animated = false; + target.animatingX = false; + target.animatingY = false; + }, duration); + } + } + }; + } + function repaint(target) { + return target.offsetWidth; + } + function calculateRealTime(animatingRect, fromRect, toRect, options) { + return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation; + } + + var plugins = []; + var defaults = { + initializeByDefault: true + }; + var PluginManager = { + mount: function mount(plugin) { + // Set default static properties + for (var option in defaults) { + if (defaults.hasOwnProperty(option) && !(option in plugin)) { + plugin[option] = defaults[option]; + } + } + plugins.forEach(function (p) { + if (p.pluginName === plugin.pluginName) { + throw "Sortable: Cannot mount plugin ".concat(plugin.pluginName, " more than once"); + } + }); + plugins.push(plugin); + }, + pluginEvent: function pluginEvent(eventName, sortable, evt) { + var _this = this; + this.eventCanceled = false; + evt.cancel = function () { + _this.eventCanceled = true; + }; + var eventNameGlobal = eventName + 'Global'; + plugins.forEach(function (plugin) { + if (!sortable[plugin.pluginName]) return; + // Fire global events if it exists in this sortable + if (sortable[plugin.pluginName][eventNameGlobal]) { + sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({ + sortable: sortable + }, evt)); + } + + // Only fire plugin event if plugin is enabled in this sortable, + // and plugin has event defined + if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) { + sortable[plugin.pluginName][eventName](_objectSpread2({ + sortable: sortable + }, evt)); + } + }); + }, + initializePlugins: function initializePlugins(sortable, el, defaults, options) { + plugins.forEach(function (plugin) { + var pluginName = plugin.pluginName; + if (!sortable.options[pluginName] && !plugin.initializeByDefault) return; + var initialized = new plugin(sortable, el, sortable.options); + initialized.sortable = sortable; + initialized.options = sortable.options; + sortable[pluginName] = initialized; + + // Add default options from plugin + _extends(defaults, initialized.defaults); + }); + for (var option in sortable.options) { + if (!sortable.options.hasOwnProperty(option)) continue; + var modified = this.modifyOption(sortable, option, sortable.options[option]); + if (typeof modified !== 'undefined') { + sortable.options[option] = modified; + } + } + }, + getEventProperties: function getEventProperties(name, sortable) { + var eventProperties = {}; + plugins.forEach(function (plugin) { + if (typeof plugin.eventProperties !== 'function') return; + _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name)); + }); + return eventProperties; + }, + modifyOption: function modifyOption(sortable, name, value) { + var modifiedValue; + plugins.forEach(function (plugin) { + // Plugin must exist on the Sortable + if (!sortable[plugin.pluginName]) return; + + // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin + if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') { + modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value); + } + }); + return modifiedValue; + } + }; + + function dispatchEvent(_ref) { + var sortable = _ref.sortable, + rootEl = _ref.rootEl, + name = _ref.name, + targetEl = _ref.targetEl, + cloneEl = _ref.cloneEl, + toEl = _ref.toEl, + fromEl = _ref.fromEl, + oldIndex = _ref.oldIndex, + newIndex = _ref.newIndex, + oldDraggableIndex = _ref.oldDraggableIndex, + newDraggableIndex = _ref.newDraggableIndex, + originalEvent = _ref.originalEvent, + putSortable = _ref.putSortable, + extraEventProperties = _ref.extraEventProperties; + sortable = sortable || rootEl && rootEl[expando]; + if (!sortable) return; + var evt, + options = sortable.options, + onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); + // Support for new CustomEvent feature + if (window.CustomEvent && !IE11OrLess && !Edge) { + evt = new CustomEvent(name, { + bubbles: true, + cancelable: true + }); + } else { + evt = document.createEvent('Event'); + evt.initEvent(name, true, true); + } + evt.to = toEl || rootEl; + evt.from = fromEl || rootEl; + evt.item = targetEl || rootEl; + evt.clone = cloneEl; + evt.oldIndex = oldIndex; + evt.newIndex = newIndex; + evt.oldDraggableIndex = oldDraggableIndex; + evt.newDraggableIndex = newDraggableIndex; + evt.originalEvent = originalEvent; + evt.pullMode = putSortable ? putSortable.lastPutMode : undefined; + var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable)); + for (var option in allEventProperties) { + evt[option] = allEventProperties[option]; + } + if (rootEl) { + rootEl.dispatchEvent(evt); + } + if (options[onName]) { + options[onName].call(sortable, evt); + } + } + + var _excluded = ["evt"]; + var pluginEvent = function pluginEvent(eventName, sortable) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + originalEvent = _ref.evt, + data = _objectWithoutProperties(_ref, _excluded); + PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({ + dragEl: dragEl, + parentEl: parentEl, + ghostEl: ghostEl, + rootEl: rootEl, + nextEl: nextEl, + lastDownEl: lastDownEl, + cloneEl: cloneEl, + cloneHidden: cloneHidden, + dragStarted: moved, + putSortable: putSortable, + activeSortable: Sortable.active, + originalEvent: originalEvent, + oldIndex: oldIndex, + oldDraggableIndex: oldDraggableIndex, + newIndex: newIndex, + newDraggableIndex: newDraggableIndex, + hideGhostForTarget: _hideGhostForTarget, + unhideGhostForTarget: _unhideGhostForTarget, + cloneNowHidden: function cloneNowHidden() { + cloneHidden = true; + }, + cloneNowShown: function cloneNowShown() { + cloneHidden = false; + }, + dispatchSortableEvent: function dispatchSortableEvent(name) { + _dispatchEvent({ + sortable: sortable, + name: name, + originalEvent: originalEvent + }); + } + }, data)); + }; + function _dispatchEvent(info) { + dispatchEvent(_objectSpread2({ + putSortable: putSortable, + cloneEl: cloneEl, + targetEl: dragEl, + rootEl: rootEl, + oldIndex: oldIndex, + oldDraggableIndex: oldDraggableIndex, + newIndex: newIndex, + newDraggableIndex: newDraggableIndex + }, info)); + } + var dragEl, + parentEl, + ghostEl, + rootEl, + nextEl, + lastDownEl, + cloneEl, + cloneHidden, + oldIndex, + newIndex, + oldDraggableIndex, + newDraggableIndex, + activeGroup, + putSortable, + awaitingDragStarted = false, + ignoreNextClick = false, + sortables = [], + tapEvt, + touchEvt, + lastDx, + lastDy, + tapDistanceLeft, + tapDistanceTop, + moved, + lastTarget, + lastDirection, + pastFirstInvertThresh = false, + isCircumstantialInvert = false, + targetMoveDistance, + // For positioning ghost absolutely + ghostRelativeParent, + ghostRelativeParentInitialScroll = [], + // (left, top) + + _silent = false, + savedInputChecked = []; + + /** @const */ + var documentExists = typeof document !== 'undefined', + PositionGhostAbsolutely = IOS, + CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float', + // This will not pass for IE9, because IE9 DnD only works on anchors + supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'), + supportCssPointerEvents = function () { + if (!documentExists) return; + // false when <= IE11 + if (IE11OrLess) { + return false; + } + var el = document.createElement('x'); + el.style.cssText = 'pointer-events:auto'; + return el.style.pointerEvents === 'auto'; + }(), + _detectDirection = function _detectDirection(el, options) { + var elCSS = css(el), + elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth), + child1 = getChild(el, 0, options), + child2 = getChild(el, 1, options), + firstChildCSS = child1 && css(child1), + secondChildCSS = child2 && css(child2), + firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width, + secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width; + if (elCSS.display === 'flex') { + return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal'; + } + if (elCSS.display === 'grid') { + return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal'; + } + if (child1 && firstChildCSS["float"] && firstChildCSS["float"] !== 'none') { + var touchingSideChild2 = firstChildCSS["float"] === 'left' ? 'left' : 'right'; + return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal'; + } + return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal'; + }, + _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) { + var dragElS1Opp = vertical ? dragRect.left : dragRect.top, + dragElS2Opp = vertical ? dragRect.right : dragRect.bottom, + dragElOppLength = vertical ? dragRect.width : dragRect.height, + targetS1Opp = vertical ? targetRect.left : targetRect.top, + targetS2Opp = vertical ? targetRect.right : targetRect.bottom, + targetOppLength = vertical ? targetRect.width : targetRect.height; + return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2; + }, + /** + * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold. + * @param {Number} x X position + * @param {Number} y Y position + * @return {HTMLElement} Element of the first found nearest Sortable + */ + _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) { + var ret; + sortables.some(function (sortable) { + var threshold = sortable[expando].options.emptyInsertThreshold; + if (!threshold || lastChild(sortable)) return; + var rect = getRect(sortable), + insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold, + insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold; + if (insideHorizontally && insideVertically) { + return ret = sortable; + } + }); + return ret; + }, + _prepareGroup = function _prepareGroup(options) { + function toFn(value, pull) { + return function (to, from, dragEl, evt) { + var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name; + if (value == null && (pull || sameGroup)) { + // Default pull value + // Default pull and put value if same group + return true; + } else if (value == null || value === false) { + return false; + } else if (pull && value === 'clone') { + return value; + } else if (typeof value === 'function') { + return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt); + } else { + var otherGroup = (pull ? to : from).options.group.name; + return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1; + } + }; + } + var group = {}; + var originalGroup = options.group; + if (!originalGroup || _typeof(originalGroup) != 'object') { + originalGroup = { + name: originalGroup + }; + } + group.name = originalGroup.name; + group.checkPull = toFn(originalGroup.pull, true); + group.checkPut = toFn(originalGroup.put); + group.revertClone = originalGroup.revertClone; + options.group = group; + }, + _hideGhostForTarget = function _hideGhostForTarget() { + if (!supportCssPointerEvents && ghostEl) { + css(ghostEl, 'display', 'none'); + } + }, + _unhideGhostForTarget = function _unhideGhostForTarget() { + if (!supportCssPointerEvents && ghostEl) { + css(ghostEl, 'display', ''); + } + }; + + // #1184 fix - Prevent click event on fallback if dragged but item not changed position + if (documentExists && !ChromeForAndroid) { + document.addEventListener('click', function (evt) { + if (ignoreNextClick) { + evt.preventDefault(); + evt.stopPropagation && evt.stopPropagation(); + evt.stopImmediatePropagation && evt.stopImmediatePropagation(); + ignoreNextClick = false; + return false; + } + }, true); + } + var nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) { + if (dragEl) { + evt = evt.touches ? evt.touches[0] : evt; + var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY); + if (nearest) { + // Create imitation event + var event = {}; + for (var i in evt) { + if (evt.hasOwnProperty(i)) { + event[i] = evt[i]; + } + } + event.target = event.rootEl = nearest; + event.preventDefault = void 0; + event.stopPropagation = void 0; + nearest[expando]._onDragOver(event); + } + } + }; + var _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) { + if (dragEl) { + dragEl.parentNode[expando]._isOutsideThisEl(evt.target); + } + }; + + /** + * @class Sortable + * @param {HTMLElement} el + * @param {Object} [options] + */ + function Sortable(el, options) { + if (!(el && el.nodeType && el.nodeType === 1)) { + throw "Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el)); + } + this.el = el; // root element + this.options = options = _extends({}, options); + + // Export instance + el[expando] = this; + var defaults = { + group: null, + sort: true, + disabled: false, + store: null, + handle: null, + draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*', + swapThreshold: 1, + // percentage; 0 <= x <= 1 + invertSwap: false, + // invert always + invertedSwapThreshold: null, + // will be set to same as swapThreshold if default + removeCloneOnHide: true, + direction: function direction() { + return _detectDirection(el, this.options); + }, + ghostClass: 'sortable-ghost', + chosenClass: 'sortable-chosen', + dragClass: 'sortable-drag', + ignore: 'a, img', + filter: null, + preventOnFilter: true, + animation: 0, + easing: null, + setData: function setData(dataTransfer, dragEl) { + dataTransfer.setData('Text', dragEl.textContent); + }, + dropBubble: false, + dragoverBubble: false, + dataIdAttr: 'data-id', + delay: 0, + delayOnTouchOnly: false, + touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1, + forceFallback: false, + fallbackClass: 'sortable-fallback', + fallbackOnBody: false, + fallbackTolerance: 0, + fallbackOffset: { + x: 0, + y: 0 + }, + // Disabled on Safari: #1571; Enabled on Safari IOS: #2244 + supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && (!Safari || IOS), + emptyInsertThreshold: 5 + }; + PluginManager.initializePlugins(this, el, defaults); + + // Set default options + for (var name in defaults) { + !(name in options) && (options[name] = defaults[name]); + } + _prepareGroup(options); + + // Bind all private methods + for (var fn in this) { + if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { + this[fn] = this[fn].bind(this); + } + } + + // Setup drag mode + this.nativeDraggable = options.forceFallback ? false : supportDraggable; + if (this.nativeDraggable) { + // Touch start threshold cannot be greater than the native dragstart threshold + this.options.touchStartThreshold = 1; + } + + // Bind events + if (options.supportPointer) { + on(el, 'pointerdown', this._onTapStart); + } else { + on(el, 'mousedown', this._onTapStart); + on(el, 'touchstart', this._onTapStart); + } + if (this.nativeDraggable) { + on(el, 'dragover', this); + on(el, 'dragenter', this); + } + sortables.push(this.el); + + // Restore sorting + options.store && options.store.get && this.sort(options.store.get(this) || []); + + // Add animation state manager + _extends(this, AnimationStateManager()); + } + Sortable.prototype = /** @lends Sortable.prototype */{ + constructor: Sortable, + _isOutsideThisEl: function _isOutsideThisEl(target) { + if (!this.el.contains(target) && target !== this.el) { + lastTarget = null; + } + }, + _getDirection: function _getDirection(evt, target) { + return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction; + }, + _onTapStart: function _onTapStart( /** Event|TouchEvent */evt) { + if (!evt.cancelable) return; + var _this = this, + el = this.el, + options = this.options, + preventOnFilter = options.preventOnFilter, + type = evt.type, + touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt, + target = (touch || evt).target, + originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target, + filter = options.filter; + _saveInputCheckedState(el); + + // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group. + if (dragEl) { + return; + } + if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) { + return; // only left button and enabled + } + + // cancel dnd if original target is content editable + if (originalTarget.isContentEditable) { + return; + } + + // Safari ignores further event handling after mousedown + if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') { + return; + } + target = closest(target, options.draggable, el, false); + if (target && target.animated) { + return; + } + if (lastDownEl === target) { + // Ignoring duplicate `down` + return; + } + + // Get the index of the dragged element within its parent + oldIndex = index(target); + oldDraggableIndex = index(target, options.draggable); + + // Check filter + if (typeof filter === 'function') { + if (filter.call(this, evt, target, this)) { + _dispatchEvent({ + sortable: _this, + rootEl: originalTarget, + name: 'filter', + targetEl: target, + toEl: el, + fromEl: el + }); + pluginEvent('filter', _this, { + evt: evt + }); + preventOnFilter && evt.preventDefault(); + return; // cancel dnd + } + } else if (filter) { + filter = filter.split(',').some(function (criteria) { + criteria = closest(originalTarget, criteria.trim(), el, false); + if (criteria) { + _dispatchEvent({ + sortable: _this, + rootEl: criteria, + name: 'filter', + targetEl: target, + fromEl: el, + toEl: el + }); + pluginEvent('filter', _this, { + evt: evt + }); + return true; + } + }); + if (filter) { + preventOnFilter && evt.preventDefault(); + return; // cancel dnd + } + } + if (options.handle && !closest(originalTarget, options.handle, el, false)) { + return; + } + + // Prepare `dragstart` + this._prepareDragStart(evt, touch, target); + }, + _prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target) { + var _this = this, + el = _this.el, + options = _this.options, + ownerDocument = el.ownerDocument, + dragStartFn; + if (target && !dragEl && target.parentNode === el) { + var dragRect = getRect(target); + rootEl = el; + dragEl = target; + parentEl = dragEl.parentNode; + nextEl = dragEl.nextSibling; + lastDownEl = target; + activeGroup = options.group; + Sortable.dragged = dragEl; + tapEvt = { + target: dragEl, + clientX: (touch || evt).clientX, + clientY: (touch || evt).clientY + }; + tapDistanceLeft = tapEvt.clientX - dragRect.left; + tapDistanceTop = tapEvt.clientY - dragRect.top; + this._lastX = (touch || evt).clientX; + this._lastY = (touch || evt).clientY; + dragEl.style['will-change'] = 'all'; + dragStartFn = function dragStartFn() { + pluginEvent('delayEnded', _this, { + evt: evt + }); + if (Sortable.eventCanceled) { + _this._onDrop(); + return; + } + // Delayed drag has been triggered + // we can re-enable the events: touchmove/mousemove + _this._disableDelayedDragEvents(); + if (!FireFox && _this.nativeDraggable) { + dragEl.draggable = true; + } + + // Bind the events: dragstart/dragend + _this._triggerDragStart(evt, touch); + + // Drag start event + _dispatchEvent({ + sortable: _this, + name: 'choose', + originalEvent: evt + }); + + // Chosen item + toggleClass(dragEl, options.chosenClass, true); + }; + + // Disable "draggable" + options.ignore.split(',').forEach(function (criteria) { + find(dragEl, criteria.trim(), _disableDraggable); + }); + on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent); + on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent); + on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent); + if (options.supportPointer) { + on(ownerDocument, 'pointerup', _this._onDrop); + // Native D&D triggers pointercancel + !this.nativeDraggable && on(ownerDocument, 'pointercancel', _this._onDrop); + } else { + on(ownerDocument, 'mouseup', _this._onDrop); + on(ownerDocument, 'touchend', _this._onDrop); + on(ownerDocument, 'touchcancel', _this._onDrop); + } + + // Make dragEl draggable (must be before delay for FireFox) + if (FireFox && this.nativeDraggable) { + this.options.touchStartThreshold = 4; + dragEl.draggable = true; + } + pluginEvent('delayStart', this, { + evt: evt + }); + + // Delay is impossible for native DnD in Edge or IE + if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) { + if (Sortable.eventCanceled) { + this._onDrop(); + return; + } + // If the user moves the pointer or let go the click or touch + // before the delay has been reached: + // disable the delayed drag + if (options.supportPointer) { + on(ownerDocument, 'pointerup', _this._disableDelayedDrag); + on(ownerDocument, 'pointercancel', _this._disableDelayedDrag); + } else { + on(ownerDocument, 'mouseup', _this._disableDelayedDrag); + on(ownerDocument, 'touchend', _this._disableDelayedDrag); + on(ownerDocument, 'touchcancel', _this._disableDelayedDrag); + } + on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler); + on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler); + options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler); + _this._dragStartTimer = setTimeout(dragStartFn, options.delay); + } else { + dragStartFn(); + } + } + }, + _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler( /** TouchEvent|PointerEvent **/e) { + var touch = e.touches ? e.touches[0] : e; + if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) { + this._disableDelayedDrag(); + } + }, + _disableDelayedDrag: function _disableDelayedDrag() { + dragEl && _disableDraggable(dragEl); + clearTimeout(this._dragStartTimer); + this._disableDelayedDragEvents(); + }, + _disableDelayedDragEvents: function _disableDelayedDragEvents() { + var ownerDocument = this.el.ownerDocument; + off(ownerDocument, 'mouseup', this._disableDelayedDrag); + off(ownerDocument, 'touchend', this._disableDelayedDrag); + off(ownerDocument, 'touchcancel', this._disableDelayedDrag); + off(ownerDocument, 'pointerup', this._disableDelayedDrag); + off(ownerDocument, 'pointercancel', this._disableDelayedDrag); + off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler); + off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler); + off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler); + }, + _triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) { + touch = touch || evt.pointerType == 'touch' && evt; + if (!this.nativeDraggable || touch) { + if (this.options.supportPointer) { + on(document, 'pointermove', this._onTouchMove); + } else if (touch) { + on(document, 'touchmove', this._onTouchMove); + } else { + on(document, 'mousemove', this._onTouchMove); + } + } else { + on(dragEl, 'dragend', this); + on(rootEl, 'dragstart', this._onDragStart); + } + try { + if (document.selection) { + _nextTick(function () { + document.selection.empty(); + }); + } else { + window.getSelection().removeAllRanges(); + } + } catch (err) {} + }, + _dragStarted: function _dragStarted(fallback, evt) { + awaitingDragStarted = false; + if (rootEl && dragEl) { + pluginEvent('dragStarted', this, { + evt: evt + }); + if (this.nativeDraggable) { + on(document, 'dragover', _checkOutsideTargetEl); + } + var options = this.options; + + // Apply effect + !fallback && toggleClass(dragEl, options.dragClass, false); + toggleClass(dragEl, options.ghostClass, true); + Sortable.active = this; + fallback && this._appendGhost(); + + // Drag start event + _dispatchEvent({ + sortable: this, + name: 'start', + originalEvent: evt + }); + } else { + this._nulling(); + } + }, + _emulateDragOver: function _emulateDragOver() { + if (touchEvt) { + this._lastX = touchEvt.clientX; + this._lastY = touchEvt.clientY; + _hideGhostForTarget(); + var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY); + var parent = target; + while (target && target.shadowRoot) { + target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY); + if (target === parent) break; + parent = target; + } + dragEl.parentNode[expando]._isOutsideThisEl(target); + if (parent) { + do { + if (parent[expando]) { + var inserted = void 0; + inserted = parent[expando]._onDragOver({ + clientX: touchEvt.clientX, + clientY: touchEvt.clientY, + target: target, + rootEl: parent + }); + if (inserted && !this.options.dragoverBubble) { + break; + } + } + target = parent; // store last element + } + /* jshint boss:true */ while (parent = getParentOrHost(parent)); + } + _unhideGhostForTarget(); + } + }, + _onTouchMove: function _onTouchMove( /**TouchEvent*/evt) { + if (tapEvt) { + var options = this.options, + fallbackTolerance = options.fallbackTolerance, + fallbackOffset = options.fallbackOffset, + touch = evt.touches ? evt.touches[0] : evt, + ghostMatrix = ghostEl && matrix(ghostEl, true), + scaleX = ghostEl && ghostMatrix && ghostMatrix.a, + scaleY = ghostEl && ghostMatrix && ghostMatrix.d, + relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent), + dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1), + dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1); + + // only set the status to dragging, when we are actually dragging + if (!Sortable.active && !awaitingDragStarted) { + if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) { + return; + } + this._onDragStart(evt, true); + } + if (ghostEl) { + if (ghostMatrix) { + ghostMatrix.e += dx - (lastDx || 0); + ghostMatrix.f += dy - (lastDy || 0); + } else { + ghostMatrix = { + a: 1, + b: 0, + c: 0, + d: 1, + e: dx, + f: dy + }; + } + var cssMatrix = "matrix(".concat(ghostMatrix.a, ",").concat(ghostMatrix.b, ",").concat(ghostMatrix.c, ",").concat(ghostMatrix.d, ",").concat(ghostMatrix.e, ",").concat(ghostMatrix.f, ")"); + css(ghostEl, 'webkitTransform', cssMatrix); + css(ghostEl, 'mozTransform', cssMatrix); + css(ghostEl, 'msTransform', cssMatrix); + css(ghostEl, 'transform', cssMatrix); + lastDx = dx; + lastDy = dy; + touchEvt = touch; + } + evt.cancelable && evt.preventDefault(); + } + }, + _appendGhost: function _appendGhost() { + // Bug if using scale(): https://stackoverflow.com/questions/2637058 + // Not being adjusted for + if (!ghostEl) { + var container = this.options.fallbackOnBody ? document.body : rootEl, + rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container), + options = this.options; + + // Position absolutely + if (PositionGhostAbsolutely) { + // Get relatively positioned parent + ghostRelativeParent = container; + while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) { + ghostRelativeParent = ghostRelativeParent.parentNode; + } + if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) { + if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement(); + rect.top += ghostRelativeParent.scrollTop; + rect.left += ghostRelativeParent.scrollLeft; + } else { + ghostRelativeParent = getWindowScrollingElement(); + } + ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent); + } + ghostEl = dragEl.cloneNode(true); + toggleClass(ghostEl, options.ghostClass, false); + toggleClass(ghostEl, options.fallbackClass, true); + toggleClass(ghostEl, options.dragClass, true); + css(ghostEl, 'transition', ''); + css(ghostEl, 'transform', ''); + css(ghostEl, 'box-sizing', 'border-box'); + css(ghostEl, 'margin', 0); + css(ghostEl, 'top', rect.top); + css(ghostEl, 'left', rect.left); + css(ghostEl, 'width', rect.width); + css(ghostEl, 'height', rect.height); + css(ghostEl, 'opacity', '0.8'); + css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed'); + css(ghostEl, 'zIndex', '100000'); + css(ghostEl, 'pointerEvents', 'none'); + Sortable.ghost = ghostEl; + container.appendChild(ghostEl); + + // Set transform-origin + css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%'); + } + }, + _onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/fallback) { + var _this = this; + var dataTransfer = evt.dataTransfer; + var options = _this.options; + pluginEvent('dragStart', this, { + evt: evt + }); + if (Sortable.eventCanceled) { + this._onDrop(); + return; + } + pluginEvent('setupClone', this); + if (!Sortable.eventCanceled) { + cloneEl = clone(dragEl); + cloneEl.removeAttribute("id"); + cloneEl.draggable = false; + cloneEl.style['will-change'] = ''; + this._hideClone(); + toggleClass(cloneEl, this.options.chosenClass, false); + Sortable.clone = cloneEl; + } + + // #1143: IFrame support workaround + _this.cloneId = _nextTick(function () { + pluginEvent('clone', _this); + if (Sortable.eventCanceled) return; + if (!_this.options.removeCloneOnHide) { + rootEl.insertBefore(cloneEl, dragEl); + } + _this._hideClone(); + _dispatchEvent({ + sortable: _this, + name: 'clone' + }); + }); + !fallback && toggleClass(dragEl, options.dragClass, true); + + // Set proper drop events + if (fallback) { + ignoreNextClick = true; + _this._loopId = setInterval(_this._emulateDragOver, 50); + } else { + // Undo what was set in _prepareDragStart before drag started + off(document, 'mouseup', _this._onDrop); + off(document, 'touchend', _this._onDrop); + off(document, 'touchcancel', _this._onDrop); + if (dataTransfer) { + dataTransfer.effectAllowed = 'move'; + options.setData && options.setData.call(_this, dataTransfer, dragEl); + } + on(document, 'drop', _this); + + // #1276 fix: + css(dragEl, 'transform', 'translateZ(0)'); + } + awaitingDragStarted = true; + _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt)); + on(document, 'selectstart', _this); + moved = true; + window.getSelection().removeAllRanges(); + if (Safari) { + css(document.body, 'user-select', 'none'); + } + }, + // Returns true - if no further action is needed (either inserted or another condition) + _onDragOver: function _onDragOver( /**Event*/evt) { + var el = this.el, + target = evt.target, + dragRect, + targetRect, + revert, + options = this.options, + group = options.group, + activeSortable = Sortable.active, + isOwner = activeGroup === group, + canSort = options.sort, + fromSortable = putSortable || activeSortable, + vertical, + _this = this, + completedFired = false; + if (_silent) return; + function dragOverEvent(name, extra) { + pluginEvent(name, _this, _objectSpread2({ + evt: evt, + isOwner: isOwner, + axis: vertical ? 'vertical' : 'horizontal', + revert: revert, + dragRect: dragRect, + targetRect: targetRect, + canSort: canSort, + fromSortable: fromSortable, + target: target, + completed: completed, + onMove: function onMove(target, after) { + return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after); + }, + changed: changed + }, extra)); + } + + // Capture animation state + function capture() { + dragOverEvent('dragOverAnimationCapture'); + _this.captureAnimationState(); + if (_this !== fromSortable) { + fromSortable.captureAnimationState(); + } + } + + // Return invocation when dragEl is inserted (or completed) + function completed(insertion) { + dragOverEvent('dragOverCompleted', { + insertion: insertion + }); + if (insertion) { + // Clones must be hidden before folding animation to capture dragRectAbsolute properly + if (isOwner) { + activeSortable._hideClone(); + } else { + activeSortable._showClone(_this); + } + if (_this !== fromSortable) { + // Set ghost class to new sortable's ghost class + toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false); + toggleClass(dragEl, options.ghostClass, true); + } + if (putSortable !== _this && _this !== Sortable.active) { + putSortable = _this; + } else if (_this === Sortable.active && putSortable) { + putSortable = null; + } + + // Animation + if (fromSortable === _this) { + _this._ignoreWhileAnimating = target; + } + _this.animateAll(function () { + dragOverEvent('dragOverAnimationComplete'); + _this._ignoreWhileAnimating = null; + }); + if (_this !== fromSortable) { + fromSortable.animateAll(); + fromSortable._ignoreWhileAnimating = null; + } + } + + // Null lastTarget if it is not inside a previously swapped element + if (target === dragEl && !dragEl.animated || target === el && !target.animated) { + lastTarget = null; + } + + // no bubbling and not fallback + if (!options.dragoverBubble && !evt.rootEl && target !== document) { + dragEl.parentNode[expando]._isOutsideThisEl(evt.target); + + // Do not detect for empty insert if already inserted + !insertion && nearestEmptyInsertDetectEvent(evt); + } + !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation(); + return completedFired = true; + } + + // Call when dragEl has been inserted + function changed() { + newIndex = index(dragEl); + newDraggableIndex = index(dragEl, options.draggable); + _dispatchEvent({ + sortable: _this, + name: 'change', + toEl: el, + newIndex: newIndex, + newDraggableIndex: newDraggableIndex, + originalEvent: evt + }); + } + if (evt.preventDefault !== void 0) { + evt.cancelable && evt.preventDefault(); + } + target = closest(target, options.draggable, el, true); + dragOverEvent('dragOver'); + if (Sortable.eventCanceled) return completedFired; + if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) { + return completed(false); + } + ignoreNextClick = false; + if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list + : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) { + vertical = this._getDirection(evt, target) === 'vertical'; + dragRect = getRect(dragEl); + dragOverEvent('dragOverValid'); + if (Sortable.eventCanceled) return completedFired; + if (revert) { + parentEl = rootEl; // actualization + capture(); + this._hideClone(); + dragOverEvent('revert'); + if (!Sortable.eventCanceled) { + if (nextEl) { + rootEl.insertBefore(dragEl, nextEl); + } else { + rootEl.appendChild(dragEl); + } + } + return completed(true); + } + var elLastChild = lastChild(el, options.draggable); + if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) { + // Insert to end of list + + // If already at end of list: Do not insert + if (elLastChild === dragEl) { + return completed(false); + } + + // if there is a last element, it is the target + if (elLastChild && el === evt.target) { + target = elLastChild; + } + if (target) { + targetRect = getRect(target); + } + if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) { + capture(); + if (elLastChild && elLastChild.nextSibling) { + // the last draggable element is not the last node + el.insertBefore(dragEl, elLastChild.nextSibling); + } else { + el.appendChild(dragEl); + } + parentEl = el; // actualization + + changed(); + return completed(true); + } + } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) { + // Insert to start of list + var firstChild = getChild(el, 0, options, true); + if (firstChild === dragEl) { + return completed(false); + } + target = firstChild; + targetRect = getRect(target); + if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) { + capture(); + el.insertBefore(dragEl, firstChild); + parentEl = el; // actualization + + changed(); + return completed(true); + } + } else if (target.parentNode === el) { + targetRect = getRect(target); + var direction = 0, + targetBeforeFirstSwap, + differentLevel = dragEl.parentNode !== el, + differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical), + side1 = vertical ? 'top' : 'left', + scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'), + scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0; + if (lastTarget !== target) { + targetBeforeFirstSwap = targetRect[side1]; + pastFirstInvertThresh = false; + isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel; + } + direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target); + var sibling; + if (direction !== 0) { + // Check if target is beside dragEl in respective direction (ignoring hidden elements) + var dragIndex = index(dragEl); + do { + dragIndex -= direction; + sibling = parentEl.children[dragIndex]; + } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl)); + } + // If dragEl is already beside target: Do not insert + if (direction === 0 || sibling === target) { + return completed(false); + } + lastTarget = target; + lastDirection = direction; + var nextSibling = target.nextElementSibling, + after = false; + after = direction === 1; + var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after); + if (moveVector !== false) { + if (moveVector === 1 || moveVector === -1) { + after = moveVector === 1; + } + _silent = true; + setTimeout(_unsilent, 30); + capture(); + if (after && !nextSibling) { + el.appendChild(dragEl); + } else { + target.parentNode.insertBefore(dragEl, after ? nextSibling : target); + } + + // Undo chrome's scroll adjustment (has no effect on other browsers) + if (scrolledPastTop) { + scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop); + } + parentEl = dragEl.parentNode; // actualization + + // must be done before animation + if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) { + targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]); + } + changed(); + return completed(true); + } + } + if (el.contains(dragEl)) { + return completed(false); + } + } + return false; + }, + _ignoreWhileAnimating: null, + _offMoveEvents: function _offMoveEvents() { + off(document, 'mousemove', this._onTouchMove); + off(document, 'touchmove', this._onTouchMove); + off(document, 'pointermove', this._onTouchMove); + off(document, 'dragover', nearestEmptyInsertDetectEvent); + off(document, 'mousemove', nearestEmptyInsertDetectEvent); + off(document, 'touchmove', nearestEmptyInsertDetectEvent); + }, + _offUpEvents: function _offUpEvents() { + var ownerDocument = this.el.ownerDocument; + off(ownerDocument, 'mouseup', this._onDrop); + off(ownerDocument, 'touchend', this._onDrop); + off(ownerDocument, 'pointerup', this._onDrop); + off(ownerDocument, 'pointercancel', this._onDrop); + off(ownerDocument, 'touchcancel', this._onDrop); + off(document, 'selectstart', this); + }, + _onDrop: function _onDrop( /**Event*/evt) { + var el = this.el, + options = this.options; + + // Get the index of the dragged element within its parent + newIndex = index(dragEl); + newDraggableIndex = index(dragEl, options.draggable); + pluginEvent('drop', this, { + evt: evt + }); + parentEl = dragEl && dragEl.parentNode; + + // Get again after plugin event + newIndex = index(dragEl); + newDraggableIndex = index(dragEl, options.draggable); + if (Sortable.eventCanceled) { + this._nulling(); + return; + } + awaitingDragStarted = false; + isCircumstantialInvert = false; + pastFirstInvertThresh = false; + clearInterval(this._loopId); + clearTimeout(this._dragStartTimer); + _cancelNextTick(this.cloneId); + _cancelNextTick(this._dragStartId); + + // Unbind events + if (this.nativeDraggable) { + off(document, 'drop', this); + off(el, 'dragstart', this._onDragStart); + } + this._offMoveEvents(); + this._offUpEvents(); + if (Safari) { + css(document.body, 'user-select', ''); + } + css(dragEl, 'transform', ''); + if (evt) { + if (moved) { + evt.cancelable && evt.preventDefault(); + !options.dropBubble && evt.stopPropagation(); + } + ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl); + if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') { + // Remove clone(s) + cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl); + } + if (dragEl) { + if (this.nativeDraggable) { + off(dragEl, 'dragend', this); + } + _disableDraggable(dragEl); + dragEl.style['will-change'] = ''; + + // Remove classes + // ghostClass is added in dragStarted + if (moved && !awaitingDragStarted) { + toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false); + } + toggleClass(dragEl, this.options.chosenClass, false); + + // Drag stop event + _dispatchEvent({ + sortable: this, + name: 'unchoose', + toEl: parentEl, + newIndex: null, + newDraggableIndex: null, + originalEvent: evt + }); + if (rootEl !== parentEl) { + if (newIndex >= 0) { + // Add event + _dispatchEvent({ + rootEl: parentEl, + name: 'add', + toEl: parentEl, + fromEl: rootEl, + originalEvent: evt + }); + + // Remove event + _dispatchEvent({ + sortable: this, + name: 'remove', + toEl: parentEl, + originalEvent: evt + }); + + // drag from one list and drop into another + _dispatchEvent({ + rootEl: parentEl, + name: 'sort', + toEl: parentEl, + fromEl: rootEl, + originalEvent: evt + }); + _dispatchEvent({ + sortable: this, + name: 'sort', + toEl: parentEl, + originalEvent: evt + }); + } + putSortable && putSortable.save(); + } else { + if (newIndex !== oldIndex) { + if (newIndex >= 0) { + // drag & drop within the same list + _dispatchEvent({ + sortable: this, + name: 'update', + toEl: parentEl, + originalEvent: evt + }); + _dispatchEvent({ + sortable: this, + name: 'sort', + toEl: parentEl, + originalEvent: evt + }); + } + } + } + if (Sortable.active) { + /* jshint eqnull:true */ + if (newIndex == null || newIndex === -1) { + newIndex = oldIndex; + newDraggableIndex = oldDraggableIndex; + } + _dispatchEvent({ + sortable: this, + name: 'end', + toEl: parentEl, + originalEvent: evt + }); + + // Save sorting + this.save(); + } + } + } + this._nulling(); + }, + _nulling: function _nulling() { + pluginEvent('nulling', this); + rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null; + savedInputChecked.forEach(function (el) { + el.checked = true; + }); + savedInputChecked.length = lastDx = lastDy = 0; + }, + handleEvent: function handleEvent( /**Event*/evt) { + switch (evt.type) { + case 'drop': + case 'dragend': + this._onDrop(evt); + break; + case 'dragenter': + case 'dragover': + if (dragEl) { + this._onDragOver(evt); + _globalDragOver(evt); + } + break; + case 'selectstart': + evt.preventDefault(); + break; + } + }, + /** + * Serializes the item into an array of string. + * @returns {String[]} + */ + toArray: function toArray() { + var order = [], + el, + children = this.el.children, + i = 0, + n = children.length, + options = this.options; + for (; i < n; i++) { + el = children[i]; + if (closest(el, options.draggable, this.el, false)) { + order.push(el.getAttribute(options.dataIdAttr) || _generateId(el)); + } + } + return order; + }, + /** + * Sorts the elements according to the array. + * @param {String[]} order order of the items + */ + sort: function sort(order, useAnimation) { + var items = {}, + rootEl = this.el; + this.toArray().forEach(function (id, i) { + var el = rootEl.children[i]; + if (closest(el, this.options.draggable, rootEl, false)) { + items[id] = el; + } + }, this); + useAnimation && this.captureAnimationState(); + order.forEach(function (id) { + if (items[id]) { + rootEl.removeChild(items[id]); + rootEl.appendChild(items[id]); + } + }); + useAnimation && this.animateAll(); + }, + /** + * Save the current sorting + */ + save: function save() { + var store = this.options.store; + store && store.set && store.set(this); + }, + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * @param {HTMLElement} el + * @param {String} [selector] default: `options.draggable` + * @returns {HTMLElement|null} + */ + closest: function closest$1(el, selector) { + return closest(el, selector || this.options.draggable, this.el, false); + }, + /** + * Set/get option + * @param {string} name + * @param {*} [value] + * @returns {*} + */ + option: function option(name, value) { + var options = this.options; + if (value === void 0) { + return options[name]; + } else { + var modifiedValue = PluginManager.modifyOption(this, name, value); + if (typeof modifiedValue !== 'undefined') { + options[name] = modifiedValue; + } else { + options[name] = value; + } + if (name === 'group') { + _prepareGroup(options); + } + } + }, + /** + * Destroy + */ + destroy: function destroy() { + pluginEvent('destroy', this); + var el = this.el; + el[expando] = null; + off(el, 'mousedown', this._onTapStart); + off(el, 'touchstart', this._onTapStart); + off(el, 'pointerdown', this._onTapStart); + if (this.nativeDraggable) { + off(el, 'dragover', this); + off(el, 'dragenter', this); + } + // Remove draggable attributes + Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) { + el.removeAttribute('draggable'); + }); + this._onDrop(); + this._disableDelayedDragEvents(); + sortables.splice(sortables.indexOf(this.el), 1); + this.el = el = null; + }, + _hideClone: function _hideClone() { + if (!cloneHidden) { + pluginEvent('hideClone', this); + if (Sortable.eventCanceled) return; + css(cloneEl, 'display', 'none'); + if (this.options.removeCloneOnHide && cloneEl.parentNode) { + cloneEl.parentNode.removeChild(cloneEl); + } + cloneHidden = true; + } + }, + _showClone: function _showClone(putSortable) { + if (putSortable.lastPutMode !== 'clone') { + this._hideClone(); + return; + } + if (cloneHidden) { + pluginEvent('showClone', this); + if (Sortable.eventCanceled) return; + + // show clone at dragEl or original position + if (dragEl.parentNode == rootEl && !this.options.group.revertClone) { + rootEl.insertBefore(cloneEl, dragEl); + } else if (nextEl) { + rootEl.insertBefore(cloneEl, nextEl); + } else { + rootEl.appendChild(cloneEl); + } + if (this.options.group.revertClone) { + this.animate(dragEl, cloneEl); + } + css(cloneEl, 'display', ''); + cloneHidden = false; + } + } + }; + function _globalDragOver( /**Event*/evt) { + if (evt.dataTransfer) { + evt.dataTransfer.dropEffect = 'move'; + } + evt.cancelable && evt.preventDefault(); + } + function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) { + var evt, + sortable = fromEl[expando], + onMoveFn = sortable.options.onMove, + retVal; + // Support for new CustomEvent feature + if (window.CustomEvent && !IE11OrLess && !Edge) { + evt = new CustomEvent('move', { + bubbles: true, + cancelable: true + }); + } else { + evt = document.createEvent('Event'); + evt.initEvent('move', true, true); + } + evt.to = toEl; + evt.from = fromEl; + evt.dragged = dragEl; + evt.draggedRect = dragRect; + evt.related = targetEl || toEl; + evt.relatedRect = targetRect || getRect(toEl); + evt.willInsertAfter = willInsertAfter; + evt.originalEvent = originalEvent; + fromEl.dispatchEvent(evt); + if (onMoveFn) { + retVal = onMoveFn.call(sortable, evt, originalEvent); + } + return retVal; + } + function _disableDraggable(el) { + el.draggable = false; + } + function _unsilent() { + _silent = false; + } + function _ghostIsFirst(evt, vertical, sortable) { + var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true)); + var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl); + var spacer = 10; + return vertical ? evt.clientX < childContainingRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < childContainingRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left; + } + function _ghostIsLast(evt, vertical, sortable) { + var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable)); + var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl); + var spacer = 10; + return vertical ? evt.clientX > childContainingRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > childContainingRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top; + } + function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) { + var mouseOnAxis = vertical ? evt.clientY : evt.clientX, + targetLength = vertical ? targetRect.height : targetRect.width, + targetS1 = vertical ? targetRect.top : targetRect.left, + targetS2 = vertical ? targetRect.bottom : targetRect.right, + invert = false; + if (!invertSwap) { + // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold + if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) { + // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2 + // check if past first invert threshold on side opposite of lastDirection + if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) { + // past first invert threshold, do not restrict inverted threshold to dragEl shadow + pastFirstInvertThresh = true; + } + if (!pastFirstInvertThresh) { + // dragEl shadow (target move distance shadow) + if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow + : mouseOnAxis > targetS2 - targetMoveDistance) { + return -lastDirection; + } + } else { + invert = true; + } + } else { + // Regular + if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) { + return _getInsertDirection(target); + } + } + } + invert = invert || invertSwap; + if (invert) { + // Invert of regular + if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) { + return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1; + } + } + return 0; + } + + /** + * Gets the direction dragEl must be swapped relative to target in order to make it + * seem that dragEl has been "inserted" into that element's position + * @param {HTMLElement} target The target whose position dragEl is being inserted at + * @return {Number} Direction dragEl must be swapped + */ + function _getInsertDirection(target) { + if (index(dragEl) < index(target)) { + return 1; + } else { + return -1; + } + } + + /** + * Generate id + * @param {HTMLElement} el + * @returns {String} + * @private + */ + function _generateId(el) { + var str = el.tagName + el.className + el.src + el.href + el.textContent, + i = str.length, + sum = 0; + while (i--) { + sum += str.charCodeAt(i); + } + return sum.toString(36); + } + function _saveInputCheckedState(root) { + savedInputChecked.length = 0; + var inputs = root.getElementsByTagName('input'); + var idx = inputs.length; + while (idx--) { + var el = inputs[idx]; + el.checked && savedInputChecked.push(el); + } + } + function _nextTick(fn) { + return setTimeout(fn, 0); + } + function _cancelNextTick(id) { + return clearTimeout(id); + } + + // Fixed #973: + if (documentExists) { + on(document, 'touchmove', function (evt) { + if ((Sortable.active || awaitingDragStarted) && evt.cancelable) { + evt.preventDefault(); + } + }); + } + + // Export utils + Sortable.utils = { + on: on, + off: off, + css: css, + find: find, + is: function is(el, selector) { + return !!closest(el, selector, el, false); + }, + extend: extend, + throttle: throttle, + closest: closest, + toggleClass: toggleClass, + clone: clone, + index: index, + nextTick: _nextTick, + cancelNextTick: _cancelNextTick, + detectDirection: _detectDirection, + getChild: getChild, + expando: expando + }; + + /** + * Get the Sortable instance of an element + * @param {HTMLElement} element The element + * @return {Sortable|undefined} The instance of Sortable + */ + Sortable.get = function (element) { + return element[expando]; + }; + + /** + * Mount a plugin to Sortable + * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted + */ + Sortable.mount = function () { + for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) { + plugins[_key] = arguments[_key]; + } + if (plugins[0].constructor === Array) plugins = plugins[0]; + plugins.forEach(function (plugin) { + if (!plugin.prototype || !plugin.prototype.constructor) { + throw "Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(plugin)); + } + if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils); + PluginManager.mount(plugin); + }); + }; + + /** + * Create sortable instance + * @param {HTMLElement} el + * @param {Object} [options] + */ + Sortable.create = function (el, options) { + return new Sortable(el, options); + }; + + // Export + Sortable.version = version; + + var autoScrolls = [], + scrollEl, + scrollRootEl, + scrolling = false, + lastAutoScrollX, + lastAutoScrollY, + touchEvt$1, + pointerElemChangedInterval; + function AutoScrollPlugin() { + function AutoScroll() { + this.defaults = { + scroll: true, + forceAutoScrollFallback: false, + scrollSensitivity: 30, + scrollSpeed: 10, + bubbleScroll: true + }; + + // Bind all private methods + for (var fn in this) { + if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { + this[fn] = this[fn].bind(this); + } + } + } + AutoScroll.prototype = { + dragStarted: function dragStarted(_ref) { + var originalEvent = _ref.originalEvent; + if (this.sortable.nativeDraggable) { + on(document, 'dragover', this._handleAutoScroll); + } else { + if (this.options.supportPointer) { + on(document, 'pointermove', this._handleFallbackAutoScroll); + } else if (originalEvent.touches) { + on(document, 'touchmove', this._handleFallbackAutoScroll); + } else { + on(document, 'mousemove', this._handleFallbackAutoScroll); + } + } + }, + dragOverCompleted: function dragOverCompleted(_ref2) { + var originalEvent = _ref2.originalEvent; + // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached) + if (!this.options.dragOverBubble && !originalEvent.rootEl) { + this._handleAutoScroll(originalEvent); + } + }, + drop: function drop() { + if (this.sortable.nativeDraggable) { + off(document, 'dragover', this._handleAutoScroll); + } else { + off(document, 'pointermove', this._handleFallbackAutoScroll); + off(document, 'touchmove', this._handleFallbackAutoScroll); + off(document, 'mousemove', this._handleFallbackAutoScroll); + } + clearPointerElemChangedInterval(); + clearAutoScrolls(); + cancelThrottle(); + }, + nulling: function nulling() { + touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null; + autoScrolls.length = 0; + }, + _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) { + this._handleAutoScroll(evt, true); + }, + _handleAutoScroll: function _handleAutoScroll(evt, fallback) { + var _this = this; + var x = (evt.touches ? evt.touches[0] : evt).clientX, + y = (evt.touches ? evt.touches[0] : evt).clientY, + elem = document.elementFromPoint(x, y); + touchEvt$1 = evt; + + // IE does not seem to have native autoscroll, + // Edge's autoscroll seems too conditional, + // MACOS Safari does not have autoscroll, + // Firefox and Chrome are good + if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) { + autoScroll(evt, this.options, elem, fallback); + + // Listener for pointer element change + var ogElemScroller = getParentAutoScrollElement(elem, true); + if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) { + pointerElemChangedInterval && clearPointerElemChangedInterval(); + // Detect for pointer elem change, emulating native DnD behaviour + pointerElemChangedInterval = setInterval(function () { + var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true); + if (newElem !== ogElemScroller) { + ogElemScroller = newElem; + clearAutoScrolls(); + } + autoScroll(evt, _this.options, newElem, fallback); + }, 10); + lastAutoScrollX = x; + lastAutoScrollY = y; + } + } else { + // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll + if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) { + clearAutoScrolls(); + return; + } + autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false); + } + } + }; + return _extends(AutoScroll, { + pluginName: 'scroll', + initializeByDefault: true + }); + } + function clearAutoScrolls() { + autoScrolls.forEach(function (autoScroll) { + clearInterval(autoScroll.pid); + }); + autoScrolls = []; + } + function clearPointerElemChangedInterval() { + clearInterval(pointerElemChangedInterval); + } + var autoScroll = throttle(function (evt, options, rootEl, isFallback) { + // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521 + if (!options.scroll) return; + var x = (evt.touches ? evt.touches[0] : evt).clientX, + y = (evt.touches ? evt.touches[0] : evt).clientY, + sens = options.scrollSensitivity, + speed = options.scrollSpeed, + winScroller = getWindowScrollingElement(); + var scrollThisInstance = false, + scrollCustomFn; + + // New scroll root, set scrollEl + if (scrollRootEl !== rootEl) { + scrollRootEl = rootEl; + clearAutoScrolls(); + scrollEl = options.scroll; + scrollCustomFn = options.scrollFn; + if (scrollEl === true) { + scrollEl = getParentAutoScrollElement(rootEl, true); + } + } + var layersOut = 0; + var currentParent = scrollEl; + do { + var el = currentParent, + rect = getRect(el), + top = rect.top, + bottom = rect.bottom, + left = rect.left, + right = rect.right, + width = rect.width, + height = rect.height, + canScrollX = void 0, + canScrollY = void 0, + scrollWidth = el.scrollWidth, + scrollHeight = el.scrollHeight, + elCSS = css(el), + scrollPosX = el.scrollLeft, + scrollPosY = el.scrollTop; + if (el === winScroller) { + canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible'); + canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible'); + } else { + canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll'); + canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll'); + } + var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX); + var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY); + if (!autoScrolls[layersOut]) { + for (var i = 0; i <= layersOut; i++) { + if (!autoScrolls[i]) { + autoScrolls[i] = {}; + } + } + } + if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) { + autoScrolls[layersOut].el = el; + autoScrolls[layersOut].vx = vx; + autoScrolls[layersOut].vy = vy; + clearInterval(autoScrolls[layersOut].pid); + if (vx != 0 || vy != 0) { + scrollThisInstance = true; + /* jshint loopfunc:true */ + autoScrolls[layersOut].pid = setInterval(function () { + // emulate drag over during autoscroll (fallback), emulating native DnD behaviour + if (isFallback && this.layer === 0) { + Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely + } + var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0; + var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0; + if (typeof scrollCustomFn === 'function') { + if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') { + return; + } + } + scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY); + }.bind({ + layer: layersOut + }), 24); + } + } + layersOut++; + } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false))); + scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not + }, 30); + + var drop = function drop(_ref) { + var originalEvent = _ref.originalEvent, + putSortable = _ref.putSortable, + dragEl = _ref.dragEl, + activeSortable = _ref.activeSortable, + dispatchSortableEvent = _ref.dispatchSortableEvent, + hideGhostForTarget = _ref.hideGhostForTarget, + unhideGhostForTarget = _ref.unhideGhostForTarget; + if (!originalEvent) return; + var toSortable = putSortable || activeSortable; + hideGhostForTarget(); + var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent; + var target = document.elementFromPoint(touch.clientX, touch.clientY); + unhideGhostForTarget(); + if (toSortable && !toSortable.el.contains(target)) { + dispatchSortableEvent('spill'); + this.onSpill({ + dragEl: dragEl, + putSortable: putSortable + }); + } + }; + function Revert() {} + Revert.prototype = { + startIndex: null, + dragStart: function dragStart(_ref2) { + var oldDraggableIndex = _ref2.oldDraggableIndex; + this.startIndex = oldDraggableIndex; + }, + onSpill: function onSpill(_ref3) { + var dragEl = _ref3.dragEl, + putSortable = _ref3.putSortable; + this.sortable.captureAnimationState(); + if (putSortable) { + putSortable.captureAnimationState(); + } + var nextSibling = getChild(this.sortable.el, this.startIndex, this.options); + if (nextSibling) { + this.sortable.el.insertBefore(dragEl, nextSibling); + } else { + this.sortable.el.appendChild(dragEl); + } + this.sortable.animateAll(); + if (putSortable) { + putSortable.animateAll(); + } + }, + drop: drop + }; + _extends(Revert, { + pluginName: 'revertOnSpill' + }); + function Remove() {} + Remove.prototype = { + onSpill: function onSpill(_ref4) { + var dragEl = _ref4.dragEl, + putSortable = _ref4.putSortable; + var parentSortable = putSortable || this.sortable; + parentSortable.captureAnimationState(); + dragEl.parentNode && dragEl.parentNode.removeChild(dragEl); + parentSortable.animateAll(); + }, + drop: drop + }; + _extends(Remove, { + pluginName: 'removeOnSpill' + }); + + var lastSwapEl; + function SwapPlugin() { + function Swap() { + this.defaults = { + swapClass: 'sortable-swap-highlight' + }; + } + Swap.prototype = { + dragStart: function dragStart(_ref) { + var dragEl = _ref.dragEl; + lastSwapEl = dragEl; + }, + dragOverValid: function dragOverValid(_ref2) { + var completed = _ref2.completed, + target = _ref2.target, + onMove = _ref2.onMove, + activeSortable = _ref2.activeSortable, + changed = _ref2.changed, + cancel = _ref2.cancel; + if (!activeSortable.options.swap) return; + var el = this.sortable.el, + options = this.options; + if (target && target !== el) { + var prevSwapEl = lastSwapEl; + if (onMove(target) !== false) { + toggleClass(target, options.swapClass, true); + lastSwapEl = target; + } else { + lastSwapEl = null; + } + if (prevSwapEl && prevSwapEl !== lastSwapEl) { + toggleClass(prevSwapEl, options.swapClass, false); + } + } + changed(); + completed(true); + cancel(); + }, + drop: function drop(_ref3) { + var activeSortable = _ref3.activeSortable, + putSortable = _ref3.putSortable, + dragEl = _ref3.dragEl; + var toSortable = putSortable || this.sortable; + var options = this.options; + lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false); + if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) { + if (dragEl !== lastSwapEl) { + toSortable.captureAnimationState(); + if (toSortable !== activeSortable) activeSortable.captureAnimationState(); + swapNodes(dragEl, lastSwapEl); + toSortable.animateAll(); + if (toSortable !== activeSortable) activeSortable.animateAll(); + } + } + }, + nulling: function nulling() { + lastSwapEl = null; + } + }; + return _extends(Swap, { + pluginName: 'swap', + eventProperties: function eventProperties() { + return { + swapItem: lastSwapEl + }; + } + }); + } + function swapNodes(n1, n2) { + var p1 = n1.parentNode, + p2 = n2.parentNode, + i1, + i2; + if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return; + i1 = index(n1); + i2 = index(n2); + if (p1.isEqualNode(p2) && i1 < i2) { + i2++; + } + p1.insertBefore(n2, p1.children[i1]); + p2.insertBefore(n1, p2.children[i2]); + } + + var multiDragElements = [], + multiDragClones = [], + lastMultiDragSelect, + // for selection with modifier key down (SHIFT) + multiDragSortable, + initialFolding = false, + // Initial multi-drag fold when drag started + folding = false, + // Folding any other time + dragStarted = false, + dragEl$1, + clonesFromRect, + clonesHidden; + function MultiDragPlugin() { + function MultiDrag(sortable) { + // Bind all private methods + for (var fn in this) { + if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { + this[fn] = this[fn].bind(this); + } + } + if (!sortable.options.avoidImplicitDeselect) { + if (sortable.options.supportPointer) { + on(document, 'pointerup', this._deselectMultiDrag); + } else { + on(document, 'mouseup', this._deselectMultiDrag); + on(document, 'touchend', this._deselectMultiDrag); + } + } + on(document, 'keydown', this._checkKeyDown); + on(document, 'keyup', this._checkKeyUp); + this.defaults = { + selectedClass: 'sortable-selected', + multiDragKey: null, + avoidImplicitDeselect: false, + setData: function setData(dataTransfer, dragEl) { + var data = ''; + if (multiDragElements.length && multiDragSortable === sortable) { + multiDragElements.forEach(function (multiDragElement, i) { + data += (!i ? '' : ', ') + multiDragElement.textContent; + }); + } else { + data = dragEl.textContent; + } + dataTransfer.setData('Text', data); + } + }; + } + MultiDrag.prototype = { + multiDragKeyDown: false, + isMultiDrag: false, + delayStartGlobal: function delayStartGlobal(_ref) { + var dragged = _ref.dragEl; + dragEl$1 = dragged; + }, + delayEnded: function delayEnded() { + this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1); + }, + setupClone: function setupClone(_ref2) { + var sortable = _ref2.sortable, + cancel = _ref2.cancel; + if (!this.isMultiDrag) return; + for (var i = 0; i < multiDragElements.length; i++) { + multiDragClones.push(clone(multiDragElements[i])); + multiDragClones[i].sortableIndex = multiDragElements[i].sortableIndex; + multiDragClones[i].draggable = false; + multiDragClones[i].style['will-change'] = ''; + toggleClass(multiDragClones[i], this.options.selectedClass, false); + multiDragElements[i] === dragEl$1 && toggleClass(multiDragClones[i], this.options.chosenClass, false); + } + sortable._hideClone(); + cancel(); + }, + clone: function clone(_ref3) { + var sortable = _ref3.sortable, + rootEl = _ref3.rootEl, + dispatchSortableEvent = _ref3.dispatchSortableEvent, + cancel = _ref3.cancel; + if (!this.isMultiDrag) return; + if (!this.options.removeCloneOnHide) { + if (multiDragElements.length && multiDragSortable === sortable) { + insertMultiDragClones(true, rootEl); + dispatchSortableEvent('clone'); + cancel(); + } + } + }, + showClone: function showClone(_ref4) { + var cloneNowShown = _ref4.cloneNowShown, + rootEl = _ref4.rootEl, + cancel = _ref4.cancel; + if (!this.isMultiDrag) return; + insertMultiDragClones(false, rootEl); + multiDragClones.forEach(function (clone) { + css(clone, 'display', ''); + }); + cloneNowShown(); + clonesHidden = false; + cancel(); + }, + hideClone: function hideClone(_ref5) { + var _this = this; + var sortable = _ref5.sortable, + cloneNowHidden = _ref5.cloneNowHidden, + cancel = _ref5.cancel; + if (!this.isMultiDrag) return; + multiDragClones.forEach(function (clone) { + css(clone, 'display', 'none'); + if (_this.options.removeCloneOnHide && clone.parentNode) { + clone.parentNode.removeChild(clone); + } + }); + cloneNowHidden(); + clonesHidden = true; + cancel(); + }, + dragStartGlobal: function dragStartGlobal(_ref6) { + var sortable = _ref6.sortable; + if (!this.isMultiDrag && multiDragSortable) { + multiDragSortable.multiDrag._deselectMultiDrag(); + } + multiDragElements.forEach(function (multiDragElement) { + multiDragElement.sortableIndex = index(multiDragElement); + }); + + // Sort multi-drag elements + multiDragElements = multiDragElements.sort(function (a, b) { + return a.sortableIndex - b.sortableIndex; + }); + dragStarted = true; + }, + dragStarted: function dragStarted(_ref7) { + var _this2 = this; + var sortable = _ref7.sortable; + if (!this.isMultiDrag) return; + if (this.options.sort) { + // Capture rects, + // hide multi drag elements (by positioning them absolute), + // set multi drag elements rects to dragRect, + // show multi drag elements, + // animate to rects, + // unset rects & remove from DOM + + sortable.captureAnimationState(); + if (this.options.animation) { + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement === dragEl$1) return; + css(multiDragElement, 'position', 'absolute'); + }); + var dragRect = getRect(dragEl$1, false, true, true); + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement === dragEl$1) return; + setRect(multiDragElement, dragRect); + }); + folding = true; + initialFolding = true; + } + } + sortable.animateAll(function () { + folding = false; + initialFolding = false; + if (_this2.options.animation) { + multiDragElements.forEach(function (multiDragElement) { + unsetRect(multiDragElement); + }); + } + + // Remove all auxiliary multidrag items from el, if sorting enabled + if (_this2.options.sort) { + removeMultiDragElements(); + } + }); + }, + dragOver: function dragOver(_ref8) { + var target = _ref8.target, + completed = _ref8.completed, + cancel = _ref8.cancel; + if (folding && ~multiDragElements.indexOf(target)) { + completed(false); + cancel(); + } + }, + revert: function revert(_ref9) { + var fromSortable = _ref9.fromSortable, + rootEl = _ref9.rootEl, + sortable = _ref9.sortable, + dragRect = _ref9.dragRect; + if (multiDragElements.length > 1) { + // Setup unfold animation + multiDragElements.forEach(function (multiDragElement) { + sortable.addAnimationState({ + target: multiDragElement, + rect: folding ? getRect(multiDragElement) : dragRect + }); + unsetRect(multiDragElement); + multiDragElement.fromRect = dragRect; + fromSortable.removeAnimationState(multiDragElement); + }); + folding = false; + insertMultiDragElements(!this.options.removeCloneOnHide, rootEl); + } + }, + dragOverCompleted: function dragOverCompleted(_ref10) { + var sortable = _ref10.sortable, + isOwner = _ref10.isOwner, + insertion = _ref10.insertion, + activeSortable = _ref10.activeSortable, + parentEl = _ref10.parentEl, + putSortable = _ref10.putSortable; + var options = this.options; + if (insertion) { + // Clones must be hidden before folding animation to capture dragRectAbsolute properly + if (isOwner) { + activeSortable._hideClone(); + } + initialFolding = false; + // If leaving sort:false root, or already folding - Fold to new location + if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) { + // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible + var dragRectAbsolute = getRect(dragEl$1, false, true, true); + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement === dragEl$1) return; + setRect(multiDragElement, dragRectAbsolute); + + // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted + // while folding, and so that we can capture them again because old sortable will no longer be fromSortable + parentEl.appendChild(multiDragElement); + }); + folding = true; + } + + // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out + if (!isOwner) { + // Only remove if not folding (folding will remove them anyways) + if (!folding) { + removeMultiDragElements(); + } + if (multiDragElements.length > 1) { + var clonesHiddenBefore = clonesHidden; + activeSortable._showClone(sortable); + + // Unfold animation for clones if showing from hidden + if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) { + multiDragClones.forEach(function (clone) { + activeSortable.addAnimationState({ + target: clone, + rect: clonesFromRect + }); + clone.fromRect = clonesFromRect; + clone.thisAnimationDuration = null; + }); + } + } else { + activeSortable._showClone(sortable); + } + } + } + }, + dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) { + var dragRect = _ref11.dragRect, + isOwner = _ref11.isOwner, + activeSortable = _ref11.activeSortable; + multiDragElements.forEach(function (multiDragElement) { + multiDragElement.thisAnimationDuration = null; + }); + if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) { + clonesFromRect = _extends({}, dragRect); + var dragMatrix = matrix(dragEl$1, true); + clonesFromRect.top -= dragMatrix.f; + clonesFromRect.left -= dragMatrix.e; + } + }, + dragOverAnimationComplete: function dragOverAnimationComplete() { + if (folding) { + folding = false; + removeMultiDragElements(); + } + }, + drop: function drop(_ref12) { + var evt = _ref12.originalEvent, + rootEl = _ref12.rootEl, + parentEl = _ref12.parentEl, + sortable = _ref12.sortable, + dispatchSortableEvent = _ref12.dispatchSortableEvent, + oldIndex = _ref12.oldIndex, + putSortable = _ref12.putSortable; + var toSortable = putSortable || this.sortable; + if (!evt) return; + var options = this.options, + children = parentEl.children; + + // Multi-drag selection + if (!dragStarted) { + if (options.multiDragKey && !this.multiDragKeyDown) { + this._deselectMultiDrag(); + } + toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1)); + if (!~multiDragElements.indexOf(dragEl$1)) { + multiDragElements.push(dragEl$1); + dispatchEvent({ + sortable: sortable, + rootEl: rootEl, + name: 'select', + targetEl: dragEl$1, + originalEvent: evt + }); + + // Modifier activated, select from last to dragEl + if (evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) { + var lastIndex = index(lastMultiDragSelect), + currentIndex = index(dragEl$1); + if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) { + (function () { + // Must include lastMultiDragSelect (select it), in case modified selection from no selection + // (but previous selection existed) + var n, i; + if (currentIndex > lastIndex) { + i = lastIndex; + n = currentIndex; + } else { + i = currentIndex; + n = lastIndex + 1; + } + var filter = options.filter; + for (; i < n; i++) { + if (~multiDragElements.indexOf(children[i])) continue; + // Check if element is draggable + if (!closest(children[i], options.draggable, parentEl, false)) continue; + // Check if element is filtered + var filtered = filter && (typeof filter === 'function' ? filter.call(sortable, evt, children[i], sortable) : filter.split(',').some(function (criteria) { + return closest(children[i], criteria.trim(), parentEl, false); + })); + if (filtered) continue; + toggleClass(children[i], options.selectedClass, true); + multiDragElements.push(children[i]); + dispatchEvent({ + sortable: sortable, + rootEl: rootEl, + name: 'select', + targetEl: children[i], + originalEvent: evt + }); + } + })(); + } + } else { + lastMultiDragSelect = dragEl$1; + } + multiDragSortable = toSortable; + } else { + multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1); + lastMultiDragSelect = null; + dispatchEvent({ + sortable: sortable, + rootEl: rootEl, + name: 'deselect', + targetEl: dragEl$1, + originalEvent: evt + }); + } + } + + // Multi-drag drop + if (dragStarted && this.isMultiDrag) { + folding = false; + // Do not "unfold" after around dragEl if reverted + if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) { + var dragRect = getRect(dragEl$1), + multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')'); + if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null; + toSortable.captureAnimationState(); + if (!initialFolding) { + if (options.animation) { + dragEl$1.fromRect = dragRect; + multiDragElements.forEach(function (multiDragElement) { + multiDragElement.thisAnimationDuration = null; + if (multiDragElement !== dragEl$1) { + var rect = folding ? getRect(multiDragElement) : dragRect; + multiDragElement.fromRect = rect; + + // Prepare unfold animation + toSortable.addAnimationState({ + target: multiDragElement, + rect: rect + }); + } + }); + } + + // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert + // properly they must all be removed + removeMultiDragElements(); + multiDragElements.forEach(function (multiDragElement) { + if (children[multiDragIndex]) { + parentEl.insertBefore(multiDragElement, children[multiDragIndex]); + } else { + parentEl.appendChild(multiDragElement); + } + multiDragIndex++; + }); + + // If initial folding is done, the elements may have changed position because they are now + // unfolding around dragEl, even though dragEl may not have his index changed, so update event + // must be fired here as Sortable will not. + if (oldIndex === index(dragEl$1)) { + var update = false; + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement.sortableIndex !== index(multiDragElement)) { + update = true; + return; + } + }); + if (update) { + dispatchSortableEvent('update'); + dispatchSortableEvent('sort'); + } + } + } + + // Must be done after capturing individual rects (scroll bar) + multiDragElements.forEach(function (multiDragElement) { + unsetRect(multiDragElement); + }); + toSortable.animateAll(); + } + multiDragSortable = toSortable; + } + + // Remove clones if necessary + if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') { + multiDragClones.forEach(function (clone) { + clone.parentNode && clone.parentNode.removeChild(clone); + }); + } + }, + nullingGlobal: function nullingGlobal() { + this.isMultiDrag = dragStarted = false; + multiDragClones.length = 0; + }, + destroyGlobal: function destroyGlobal() { + this._deselectMultiDrag(); + off(document, 'pointerup', this._deselectMultiDrag); + off(document, 'mouseup', this._deselectMultiDrag); + off(document, 'touchend', this._deselectMultiDrag); + off(document, 'keydown', this._checkKeyDown); + off(document, 'keyup', this._checkKeyUp); + }, + _deselectMultiDrag: function _deselectMultiDrag(evt) { + if (typeof dragStarted !== "undefined" && dragStarted) return; + + // Only deselect if selection is in this sortable + if (multiDragSortable !== this.sortable) return; + + // Only deselect if target is not item in this sortable + if (evt && closest(evt.target, this.options.draggable, this.sortable.el, false)) return; + + // Only deselect if left click + if (evt && evt.button !== 0) return; + while (multiDragElements.length) { + var el = multiDragElements[0]; + toggleClass(el, this.options.selectedClass, false); + multiDragElements.shift(); + dispatchEvent({ + sortable: this.sortable, + rootEl: this.sortable.el, + name: 'deselect', + targetEl: el, + originalEvent: evt + }); + } + }, + _checkKeyDown: function _checkKeyDown(evt) { + if (evt.key === this.options.multiDragKey) { + this.multiDragKeyDown = true; + } + }, + _checkKeyUp: function _checkKeyUp(evt) { + if (evt.key === this.options.multiDragKey) { + this.multiDragKeyDown = false; + } + } + }; + return _extends(MultiDrag, { + // Static methods & properties + pluginName: 'multiDrag', + utils: { + /** + * Selects the provided multi-drag item + * @param {HTMLElement} el The element to be selected + */ + select: function select(el) { + var sortable = el.parentNode[expando]; + if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return; + if (multiDragSortable && multiDragSortable !== sortable) { + multiDragSortable.multiDrag._deselectMultiDrag(); + multiDragSortable = sortable; + } + toggleClass(el, sortable.options.selectedClass, true); + multiDragElements.push(el); + }, + /** + * Deselects the provided multi-drag item + * @param {HTMLElement} el The element to be deselected + */ + deselect: function deselect(el) { + var sortable = el.parentNode[expando], + index = multiDragElements.indexOf(el); + if (!sortable || !sortable.options.multiDrag || !~index) return; + toggleClass(el, sortable.options.selectedClass, false); + multiDragElements.splice(index, 1); + } + }, + eventProperties: function eventProperties() { + var _this3 = this; + var oldIndicies = [], + newIndicies = []; + multiDragElements.forEach(function (multiDragElement) { + oldIndicies.push({ + multiDragElement: multiDragElement, + index: multiDragElement.sortableIndex + }); + + // multiDragElements will already be sorted if folding + var newIndex; + if (folding && multiDragElement !== dragEl$1) { + newIndex = -1; + } else if (folding) { + newIndex = index(multiDragElement, ':not(.' + _this3.options.selectedClass + ')'); + } else { + newIndex = index(multiDragElement); + } + newIndicies.push({ + multiDragElement: multiDragElement, + index: newIndex + }); + }); + return { + items: _toConsumableArray(multiDragElements), + clones: [].concat(multiDragClones), + oldIndicies: oldIndicies, + newIndicies: newIndicies + }; + }, + optionListeners: { + multiDragKey: function multiDragKey(key) { + key = key.toLowerCase(); + if (key === 'ctrl') { + key = 'Control'; + } else if (key.length > 1) { + key = key.charAt(0).toUpperCase() + key.substr(1); + } + return key; + } + } + }); + } + function insertMultiDragElements(clonesInserted, rootEl) { + multiDragElements.forEach(function (multiDragElement, i) { + var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)]; + if (target) { + rootEl.insertBefore(multiDragElement, target); + } else { + rootEl.appendChild(multiDragElement); + } + }); + } + + /** + * Insert multi-drag clones + * @param {[Boolean]} elementsInserted Whether the multi-drag elements are inserted + * @param {HTMLElement} rootEl + */ + function insertMultiDragClones(elementsInserted, rootEl) { + multiDragClones.forEach(function (clone, i) { + var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)]; + if (target) { + rootEl.insertBefore(clone, target); + } else { + rootEl.appendChild(clone); + } + }); + } + function removeMultiDragElements() { + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement === dragEl$1) return; + multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement); + }); + } + + Sortable.mount(new AutoScrollPlugin()); + Sortable.mount(Remove, Revert); + + Sortable.mount(new SwapPlugin()); + Sortable.mount(new MultiDragPlugin()); + + return Sortable; + +}))); \ No newline at end of file diff --git a/Sortable.min.js b/Sortable.min.js index 754718913..95423a649 100644 --- a/Sortable.min.js +++ b/Sortable.min.js @@ -1,2 +1,2 @@ -/*! Sortable 1.2.1 - MIT | git://github.com/rubaxa/Sortable.git */ -!function(a){"use strict";"function"==typeof define&&define.amd?define(a):"undefined"!=typeof module&&"undefined"!=typeof module.exports?module.exports=a():"undefined"!=typeof Package?Sortable=a():window.Sortable=a()}(function(){"use strict";function a(a,b){this.el=a,this.options=b=s({},b),a[J]=this;var d={group:Math.random(),sort:!0,disabled:!1,store:null,handle:null,scroll:!0,scrollSensitivity:30,scrollSpeed:10,draggable:/[uo]l/i.test(a.nodeName)?"li":">*",ghostClass:"sortable-ghost",ignore:"a, img",filter:null,animation:0,setData:function(a,b){a.setData("Text",b.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0};for(var e in d)!(e in b)&&(b[e]=d[e]);var g=b.group;g&&"object"==typeof g||(g=b.group={name:g}),["pull","put"].forEach(function(a){a in g||(g[a]=!0)}),b.groups=" "+g.name+(g.put.join?" "+g.put.join(" "):"")+" ";for(var h in this)"_"===h.charAt(0)&&(this[h]=c(this,this[h]));f(a,"mousedown",this._onTapStart),f(a,"touchstart",this._onTapStart),f(a,"dragover",this),f(a,"dragenter",this),R.push(this._onDragOver),b.store&&this.sort(b.store.get(this))}function b(a){v&&v.state!==a&&(i(v,"display",a?"none":""),!a&&v.state&&w.insertBefore(v,t),v.state=a)}function c(a,b){var c=Q.call(arguments,2);return b.bind?b.bind.apply(b,[a].concat(c)):function(){return b.apply(a,c.concat(Q.call(arguments)))}}function d(a,b,c){if(a){c=c||L,b=b.split(".");var d=b.shift().toUpperCase(),e=new RegExp("\\s("+b.join("|")+")(?=\\s)","g");do if(">*"===d&&a.parentNode===c||(""===d||a.nodeName.toUpperCase()==d)&&(!b.length||((" "+a.className+" ").match(e)||[]).length==b.length))return a;while(a!==c&&(a=a.parentNode))}return null}function e(a){a.dataTransfer.dropEffect="move",a.preventDefault()}function f(a,b,c){a.addEventListener(b,c,!1)}function g(a,b,c){a.removeEventListener(b,c,!1)}function h(a,b,c){if(a)if(a.classList)a.classList[c?"add":"remove"](b);else{var d=(" "+a.className+" ").replace(I," ").replace(" "+b+" "," ");a.className=(d+(c?" "+b:"")).replace(I," ")}}function i(a,b,c){var d=a&&a.style;if(d){if(void 0===c)return L.defaultView&&L.defaultView.getComputedStyle?c=L.defaultView.getComputedStyle(a,""):a.currentStyle&&(c=a.currentStyle),void 0===b?c:c[b];b in d||(b="-webkit-"+b),d[b]=c+("string"==typeof c?"":"px")}}function j(a,b,c){if(a){var d=a.getElementsByTagName(b),e=0,f=d.length;if(c)for(;f>e;e++)c(d[e],e);return d}return[]}function k(a,b,c,d,e,f,g){var h=L.createEvent("Event"),i=(a||b[J]).options,j="on"+c.charAt(0).toUpperCase()+c.substr(1);h.initEvent(c,!0,!0),h.to=b,h.from=e||b,h.item=d||b,h.clone=v,h.oldIndex=f,h.newIndex=g,b.dispatchEvent(h),i[j]&&i[j].call(a,h)}function l(a,b,c,d,e,f){var g,h,i=a[J],j=i.options.onMove;return j&&(g=L.createEvent("Event"),g.initEvent("move",!0,!0),g.to=b,g.from=a,g.dragged=c,g.draggedRect=d,g.related=e||b,g.relatedRect=f||b.getBoundingClientRect(),h=j.call(i,g)),h}function m(a){a.draggable=!1}function n(){O=!1}function o(a,b){var c=a.lastElementChild,d=c.getBoundingClientRect();return b.clientY-(d.top+d.height)>5&&c}function p(a){for(var b=a.tagName+a.className+a.src+a.href+a.textContent,c=b.length,d=0;c--;)d+=b.charCodeAt(c);return d.toString(36)}function q(a){for(var b=0;a&&(a=a.previousElementSibling);)"TEMPLATE"!==a.nodeName.toUpperCase()&&b++;return b}function r(a,b){var c,d;return function(){void 0===c&&(c=arguments,d=this,setTimeout(function(){1===c.length?a.call(d,c[0]):a.apply(d,c),c=void 0},b))}}function s(a,b){if(a&&b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}var t,u,v,w,x,y,z,A,B,C,D,E,F,G,H={},I=/\s+/g,J="Sortable"+(new Date).getTime(),K=window,L=K.document,M=K.parseInt,N=!!("draggable"in L.createElement("div")),O=!1,P=Math.abs,Q=[].slice,R=[],S=r(function(a,b,c){if(c&&b.scroll){var d,e,f,g,h=b.scrollSensitivity,i=b.scrollSpeed,j=a.clientX,k=a.clientY,l=window.innerWidth,m=window.innerHeight;if(z!==c&&(y=b.scroll,z=c,y===!0)){y=c;do if(y.offsetWidth=l-j)-(h>=j),g=(h>=m-k)-(h>=k),(f||g)&&(d=K)),(H.vx!==f||H.vy!==g||H.el!==d)&&(H.el=d,H.vx=f,H.vy=g,clearInterval(H.pid),d&&(H.pid=setInterval(function(){d===K?K.scrollTo(K.pageXOffset+f*i,K.pageYOffset+g*i):(g&&(d.scrollTop+=g*i),f&&(d.scrollLeft+=f*i))},24)))}},30);return a.prototype={constructor:a,_onTapStart:function(a){var b=this,c=this.el,e=this.options,f=a.type,g=a.touches&&a.touches[0],h=(g||a).target,i=h,j=e.filter;if(!("mousedown"===f&&0!==a.button||e.disabled)&&(h=d(h,e.draggable,c))){if(C=q(h),"function"==typeof j){if(j.call(this,a,h,this))return k(b,i,"filter",h,c,C),void a.preventDefault()}else if(j&&(j=j.split(",").some(function(a){return a=d(i,a.trim(),c),a?(k(b,a,"filter",h,c,C),!0):void 0})))return void a.preventDefault();(!e.handle||d(i,e.handle,c))&&this._prepareDragStart(a,g,h)}},_prepareDragStart:function(a,b,c){var d,e=this,g=e.el,h=e.options,i=g.ownerDocument;c&&!t&&c.parentNode===g&&(F=a,w=g,t=c,x=t.nextSibling,E=h.group,d=function(){e._disableDelayedDrag(),t.draggable=!0,h.ignore.split(",").forEach(function(a){j(t,a.trim(),m)}),e._triggerDragStart(b)},f(i,"mouseup",e._onDrop),f(i,"touchend",e._onDrop),f(i,"touchcancel",e._onDrop),h.delay?(f(i,"mousemove",e._disableDelayedDrag),f(i,"touchmove",e._disableDelayedDrag),e._dragStartTimer=setTimeout(d,h.delay)):d())},_disableDelayedDrag:function(){var a=this.el.ownerDocument;clearTimeout(this._dragStartTimer),g(a,"mousemove",this._disableDelayedDrag),g(a,"touchmove",this._disableDelayedDrag)},_triggerDragStart:function(a){a?(F={target:t,clientX:a.clientX,clientY:a.clientY},this._onDragStart(F,"touch")):N?(f(t,"dragend",this),f(w,"dragstart",this._onDragStart)):this._onDragStart(F,!0);try{L.selection?L.selection.empty():window.getSelection().removeAllRanges()}catch(b){}},_dragStarted:function(){w&&t&&(h(t,this.options.ghostClass,!0),a.active=this,k(this,w,"start",t,w,C))},_emulateDragOver:function(){if(G){i(u,"display","none");var a=L.elementFromPoint(G.clientX,G.clientY),b=a,c=" "+this.options.group.name,d=R.length;if(b)do{if(b[J]&&b[J].options.groups.indexOf(c)>-1){for(;d--;)R[d]({clientX:G.clientX,clientY:G.clientY,target:a,rootEl:b});break}a=b}while(b=b.parentNode);i(u,"display","")}},_onTouchMove:function(a){if(F){var b=a.touches?a.touches[0]:a,c=b.clientX-F.clientX,d=b.clientY-F.clientY,e=a.touches?"translate3d("+c+"px,"+d+"px,0)":"translate("+c+"px,"+d+"px)";G=b,i(u,"webkitTransform",e),i(u,"mozTransform",e),i(u,"msTransform",e),i(u,"transform",e),a.preventDefault()}},_onDragStart:function(a,b){var c=a.dataTransfer,d=this.options;if(this._offUpEvents(),"clone"==E.pull&&(v=t.cloneNode(!0),i(v,"display","none"),w.insertBefore(v,t)),b){var e,g=t.getBoundingClientRect(),h=i(t);u=t.cloneNode(!0),i(u,"top",g.top-M(h.marginTop,10)),i(u,"left",g.left-M(h.marginLeft,10)),i(u,"width",g.width),i(u,"height",g.height),i(u,"opacity","0.8"),i(u,"position","fixed"),i(u,"zIndex","100000"),w.appendChild(u),e=u.getBoundingClientRect(),i(u,"width",2*g.width-e.width),i(u,"height",2*g.height-e.height),"touch"===b?(f(L,"touchmove",this._onTouchMove),f(L,"touchend",this._onDrop),f(L,"touchcancel",this._onDrop)):(f(L,"mousemove",this._onTouchMove),f(L,"mouseup",this._onDrop)),this._loopId=setInterval(this._emulateDragOver,150)}else c&&(c.effectAllowed="move",d.setData&&d.setData.call(this,c,t)),f(L,"drop",this);setTimeout(this._dragStarted,0)},_onDragOver:function(a){var c,e,f,g=this.el,h=this.options,j=h.group,k=j.put,m=E===j,p=h.sort;if(void 0!==a.preventDefault&&(a.preventDefault(),!h.dragoverBubble&&a.stopPropagation()),E&&!h.disabled&&(m?p||(f=!w.contains(t)):E.pull&&k&&(E.name===j.name||k.indexOf&&~k.indexOf(E.name)))&&(void 0===a.rootEl||a.rootEl===this.el)){if(S(a,h,this.el),O)return;if(c=d(a.target,h.draggable,g),e=t.getBoundingClientRect(),f)return b(!0),void(v||x?w.insertBefore(t,v||x):p||w.appendChild(t));if(0===g.children.length||g.children[0]===u||g===a.target&&(c=o(g,a))){if(c){if(c.animated)return;r=c.getBoundingClientRect()}b(m),l(w,g,t,e,c,r)!==!1&&(g.appendChild(t),this._animate(e,t),c&&this._animate(r,c))}else if(c&&!c.animated&&c!==t&&void 0!==c.parentNode[J]){A!==c&&(A=c,B=i(c));var q,r=c.getBoundingClientRect(),s=r.right-r.left,y=r.bottom-r.top,z=/left|right|inline/.test(B.cssFloat+B.display),C=c.offsetWidth>t.offsetWidth,D=c.offsetHeight>t.offsetHeight,F=(z?(a.clientX-r.left)/s:(a.clientY-r.top)/y)>.5,G=c.nextElementSibling,H=l(w,g,t,e,c,r);H!==!1&&(O=!0,setTimeout(n,30),b(m),q=1===H||-1===H?1===H:z?c.previousElementSibling===t&&!C||F&&C:G!==t&&!D||F&&D,q&&!G?g.appendChild(t):c.parentNode.insertBefore(t,q?G:c),this._animate(e,t),this._animate(r,c))}}},_animate:function(a,b){var c=this.options.animation;if(c){var d=b.getBoundingClientRect();i(b,"transition","none"),i(b,"transform","translate3d("+(a.left-d.left)+"px,"+(a.top-d.top)+"px,0)"),b.offsetWidth,i(b,"transition","all "+c+"ms"),i(b,"transform","translate3d(0,0,0)"),clearTimeout(b.animated),b.animated=setTimeout(function(){i(b,"transition",""),i(b,"transform",""),b.animated=!1},c)}},_offUpEvents:function(){var a=this.el.ownerDocument;g(L,"touchmove",this._onTouchMove),g(a,"mouseup",this._onDrop),g(a,"touchend",this._onDrop),g(a,"touchcancel",this._onDrop)},_onDrop:function(b){var c=this.el,d=this.options;clearInterval(this._loopId),clearInterval(H.pid),clearTimeout(this._dragStartTimer),g(L,"drop",this),g(L,"mousemove",this._onTouchMove),g(c,"dragstart",this._onDragStart),this._offUpEvents(),b&&(b.preventDefault(),!d.dropBubble&&b.stopPropagation(),u&&u.parentNode.removeChild(u),t&&(g(t,"dragend",this),m(t),h(t,this.options.ghostClass,!1),w!==t.parentNode?(D=q(t),k(null,t.parentNode,"sort",t,w,C,D),k(this,w,"sort",t,w,C,D),k(null,t.parentNode,"add",t,w,C,D),k(this,w,"remove",t,w,C,D)):(v&&v.parentNode.removeChild(v),t.nextSibling!==x&&(D=q(t),k(this,w,"update",t,w,C,D),k(this,w,"sort",t,w,C,D))),a.active&&(k(this,w,"end",t,w,C,D),this.save())),w=t=u=x=v=y=z=F=G=A=B=E=a.active=null)},handleEvent:function(a){var b=a.type;"dragover"===b||"dragenter"===b?t&&(this._onDragOver(a),e(a)):("drop"===b||"dragend"===b)&&this._onDrop(a)},toArray:function(){for(var a,b=[],c=this.el.children,e=0,f=c.length,g=this.options;f>e;e++)a=c[e],d(a,g.draggable,this.el)&&b.push(a.getAttribute(g.dataIdAttr)||p(a));return b},sort:function(a){var b={},c=this.el;this.toArray().forEach(function(a,e){var f=c.children[e];d(f,this.options.draggable,c)&&(b[a]=f)},this),a.forEach(function(a){b[a]&&(c.removeChild(b[a]),c.appendChild(b[a]))})},save:function(){var a=this.options.store;a&&a.set(this)},closest:function(a,b){return d(a,b||this.options.draggable,this.el)},option:function(a,b){var c=this.options;return void 0===b?c[a]:void(c[a]=b)},destroy:function(){var a=this.el;a[J]=null,g(a,"mousedown",this._onTapStart),g(a,"touchstart",this._onTapStart),g(a,"dragover",this),g(a,"dragenter",this),Array.prototype.forEach.call(a.querySelectorAll("[draggable]"),function(a){a.removeAttribute("draggable")}),R.splice(R.indexOf(this._onDragOver),1),this._onDrop(),this.el=a=null}},a.utils={on:f,off:g,css:i,find:j,bind:c,is:function(a,b){return!!d(a,b,a)},extend:s,throttle:r,closest:d,toggleClass:h,index:q},a.version="1.2.1",a.create=function(b,c){return new a(b,c)},a}); \ No newline at end of file +/*! Sortable 1.15.6 - MIT | git://github.com/SortableJS/Sortable.git */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Sortable=e()}(this,function(){"use strict";function e(e,t){var n,o=Object.keys(e);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(e),t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,n)),o}function I(o){for(var t=1;tt.length)&&(e=t.length);for(var n=0,o=new Array(e);n"===e[0]&&(e=e.substring(1)),t))try{if(t.matches)return t.matches(e);if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch(t){return}}function g(t){return t.host&&t!==document&&t.host.nodeType?t.host:t.parentNode}function P(t,e,n,o){if(t){n=n||document;do{if(null!=e&&(">"!==e[0]||t.parentNode===n)&&f(t,e)||o&&t===n)return t}while(t!==n&&(t=g(t)))}return null}var m,v=/\s+/g;function k(t,e,n){var o;t&&e&&(t.classList?t.classList[n?"add":"remove"](e):(o=(" "+t.className+" ").replace(v," ").replace(" "+e+" "," "),t.className=(o+(n?" "+e:"")).replace(v," ")))}function R(t,e,n){var o=t&&t.style;if(o){if(void 0===n)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(t,""):t.currentStyle&&(n=t.currentStyle),void 0===e?n:n[e];o[e=!(e in o||-1!==e.indexOf("webkit"))?"-webkit-"+e:e]=n+("string"==typeof n?"":"px")}}function b(t,e){var n="";if("string"==typeof t)n=t;else do{var o=R(t,"transform")}while(o&&"none"!==o&&(n=o+" "+n),!e&&(t=t.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function D(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i=n.left-e&&i<=n.right+e,e=r>=n.top-e&&r<=n.bottom+e;return o&&e?a=t:void 0}}),a);if(e){var n,o={};for(n in t)t.hasOwnProperty(n)&&(o[n]=t[n]);o.target=o.rootEl=e,o.preventDefault=void 0,o.stopPropagation=void 0,e[K]._onDragOver(o)}}var i,r,a}function Ft(t){Z&&Z.parentNode[K]._isOutsideThisEl(t.target)}function jt(t,e){if(!t||!t.nodeType||1!==t.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=a({},e),t[K]=this;var n,o,i={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return kt(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(t,e){t.setData("Text",e.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==jt.supportPointer&&"PointerEvent"in window&&(!u||c),emptyInsertThreshold:5};for(n in z.initializePlugins(this,t,i),i)n in e||(e[n]=i[n]);for(o in Rt(e),this)"_"===o.charAt(0)&&"function"==typeof this[o]&&(this[o]=this[o].bind(this));this.nativeDraggable=!e.forceFallback&&It,this.nativeDraggable&&(this.options.touchStartThreshold=1),e.supportPointer?h(t,"pointerdown",this._onTapStart):(h(t,"mousedown",this._onTapStart),h(t,"touchstart",this._onTapStart)),this.nativeDraggable&&(h(t,"dragover",this),h(t,"dragenter",this)),St.push(this.el),e.store&&e.store.get&&this.sort(e.store.get(this)||[]),a(this,A())}function Ht(t,e,n,o,i,r,a,l){var s,c,u=t[K],d=u.options.onMove;return!window.CustomEvent||y||w?(s=document.createEvent("Event")).initEvent("move",!0,!0):s=new CustomEvent("move",{bubbles:!0,cancelable:!0}),s.to=e,s.from=t,s.dragged=n,s.draggedRect=o,s.related=i||e,s.relatedRect=r||X(e),s.willInsertAfter=l,s.originalEvent=a,t.dispatchEvent(s),c=d?d.call(u,s,a):c}function Lt(t){t.draggable=!1}function Kt(){xt=!1}function Wt(t){return setTimeout(t,0)}function zt(t){return clearTimeout(t)}jt.prototype={constructor:jt,_isOutsideThisEl:function(t){this.el.contains(t)||t===this.el||(vt=null)},_getDirection:function(t,e){return"function"==typeof this.options.direction?this.options.direction.call(this,t,e,Z):this.options.direction},_onTapStart:function(e){if(e.cancelable){var n=this,o=this.el,t=this.options,i=t.preventOnFilter,r=e.type,a=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,l=(a||e).target,s=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,c=t.filter;if(!function(t){Ot.length=0;var e=t.getElementsByTagName("input"),n=e.length;for(;n--;){var o=e[n];o.checked&&Ot.push(o)}}(o),!Z&&!(/mousedown|pointerdown/.test(r)&&0!==e.button||t.disabled)&&!s.isContentEditable&&(this.nativeDraggable||!u||!l||"SELECT"!==l.tagName.toUpperCase())&&!((l=P(l,t.draggable,o,!1))&&l.animated||et===l)){if(it=j(l),at=j(l,t.draggable),"function"==typeof c){if(c.call(this,e,l,this))return V({sortable:n,rootEl:s,name:"filter",targetEl:l,toEl:o,fromEl:o}),U("filter",n,{evt:e}),void(i&&e.preventDefault())}else if(c=c&&c.split(",").some(function(t){if(t=P(s,t.trim(),o,!1))return V({sortable:n,rootEl:t,name:"filter",targetEl:l,fromEl:o,toEl:o}),U("filter",n,{evt:e}),!0}))return void(i&&e.preventDefault());t.handle&&!P(s,t.handle,o,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(t,e,n){var o,i=this,r=i.el,a=i.options,l=r.ownerDocument;n&&!Z&&n.parentNode===r&&(o=X(n),J=r,$=(Z=n).parentNode,tt=Z.nextSibling,et=n,st=a.group,ut={target:jt.dragged=Z,clientX:(e||t).clientX,clientY:(e||t).clientY},ft=ut.clientX-o.left,gt=ut.clientY-o.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,Z.style["will-change"]="all",o=function(){U("delayEnded",i,{evt:t}),jt.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!s&&i.nativeDraggable&&(Z.draggable=!0),i._triggerDragStart(t,e),V({sortable:i,name:"choose",originalEvent:t}),k(Z,a.chosenClass,!0))},a.ignore.split(",").forEach(function(t){D(Z,t.trim(),Lt)}),h(l,"dragover",Bt),h(l,"mousemove",Bt),h(l,"touchmove",Bt),a.supportPointer?(h(l,"pointerup",i._onDrop),this.nativeDraggable||h(l,"pointercancel",i._onDrop)):(h(l,"mouseup",i._onDrop),h(l,"touchend",i._onDrop),h(l,"touchcancel",i._onDrop)),s&&this.nativeDraggable&&(this.options.touchStartThreshold=4,Z.draggable=!0),U("delayStart",this,{evt:t}),!a.delay||a.delayOnTouchOnly&&!e||this.nativeDraggable&&(w||y)?o():jt.eventCanceled?this._onDrop():(a.supportPointer?(h(l,"pointerup",i._disableDelayedDrag),h(l,"pointercancel",i._disableDelayedDrag)):(h(l,"mouseup",i._disableDelayedDrag),h(l,"touchend",i._disableDelayedDrag),h(l,"touchcancel",i._disableDelayedDrag)),h(l,"mousemove",i._delayedDragTouchMoveHandler),h(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&&h(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(o,a.delay)))},_delayedDragTouchMoveHandler:function(t){t=t.touches?t.touches[0]:t;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){Z&&Lt(Z),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;p(t,"mouseup",this._disableDelayedDrag),p(t,"touchend",this._disableDelayedDrag),p(t,"touchcancel",this._disableDelayedDrag),p(t,"pointerup",this._disableDelayedDrag),p(t,"pointercancel",this._disableDelayedDrag),p(t,"mousemove",this._delayedDragTouchMoveHandler),p(t,"touchmove",this._delayedDragTouchMoveHandler),p(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||"touch"==t.pointerType&&t,!this.nativeDraggable||e?this.options.supportPointer?h(document,"pointermove",this._onTouchMove):h(document,e?"touchmove":"mousemove",this._onTouchMove):(h(Z,"dragend",this),h(J,"dragstart",this._onDragStart));try{document.selection?Wt(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(t){}},_dragStarted:function(t,e){var n;Dt=!1,J&&Z?(U("dragStarted",this,{evt:e}),this.nativeDraggable&&h(document,"dragover",Ft),n=this.options,t||k(Z,n.dragClass,!1),k(Z,n.ghostClass,!0),jt.active=this,t&&this._appendGhost(),V({sortable:this,name:"start",originalEvent:e})):this._nulling()},_emulateDragOver:function(){if(dt){this._lastX=dt.clientX,this._lastY=dt.clientY,Xt();for(var t=document.elementFromPoint(dt.clientX,dt.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(dt.clientX,dt.clientY))!==e;)e=t;if(Z.parentNode[K]._isOutsideThisEl(t),e)do{if(e[K])if(e[K]._onDragOver({clientX:dt.clientX,clientY:dt.clientY,target:t,rootEl:e})&&!this.options.dragoverBubble)break}while(e=g(t=e));Yt()}},_onTouchMove:function(t){if(ut){var e=this.options,n=e.fallbackTolerance,o=e.fallbackOffset,i=t.touches?t.touches[0]:t,r=Q&&b(Q,!0),a=Q&&r&&r.a,l=Q&&r&&r.d,e=At&&wt&&E(wt),a=(i.clientX-ut.clientX+o.x)/(a||1)+(e?e[0]-Tt[0]:0)/(a||1),l=(i.clientY-ut.clientY+o.y)/(l||1)+(e?e[1]-Tt[1]:0)/(l||1);if(!jt.active&&!Dt){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))E.right+10||S.clientY>x.bottom&&S.clientX>x.left:S.clientY>E.bottom+10||S.clientX>x.right&&S.clientY>x.top)||m.animated)){if(m&&(t=n,e=r,C=X(B((_=this).el,0,_.options,!0)),_=L(_.el,_.options,Q),e?t.clientX<_.left-10||t.clientY" - ], - "description": "Minimalist library for reorderable drag-and-drop lists on modern browsers and touch devices. No jQuery.", - "keywords": [ - "sortable", - "reorder", - "list", - "html5", - "drag", - "and", - "drop", - "dnd" - ], - "license": "MIT", - "ignore": [ - "node_modules", - "bower_components", - "test", - "tests" - ] -} diff --git a/component.json b/component.json deleted file mode 100644 index 31a2a57e2..000000000 --- a/component.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "Sortable", - "main": "Sortable.js", - "version": "1.2.1", - "homepage": "http://rubaxa.github.io/Sortable/", - "repo": "RubaXa/Sortable", - "authors": [ - "RubaXa " - ], - "description": "Minimalist library for reorderable drag-and-drop lists on modern browsers and touch devices. No jQuery.", - "keywords": [ - "sortable", - "reorder", - "list", - "html5", - "drag", - "and", - "drop", - "dnd" - ], - "license": "MIT", - "ignore": [ - "node_modules", - "bower_components", - "test", - "tests" - ], - - "scripts": [ - "Sortable.js" - ] -} diff --git a/index.html b/index.html index c7064436e..87162e8b3 100644 --- a/index.html +++ b/index.html @@ -1,344 +1,464 @@ + + SortableJS + + + + + - - Sortable. No jQuery. - - - + + - - - - - - Fork me on GitHub + Fork me on GitHub
-
- -

The JavaScript library for modern browsers and touch devices. No jQuery.

+
+
+ +
+ +

SortableJS

+

JavaScript library for reorderable drag-and-drop lists

+ +
-
- - -
-
-
List A
-
    -
  • бегемот
  • -
  • корм
  • -
  • антон
  • -
  • сало
  • -
  • железосталь
  • -
  • валик
  • -
  • кровать
  • -
  • краб
  • -
+
+

Features

- -
-
List B
-
    -
  • казнить
  • -
  • ,
  • -
  • нельзя
  • -
  • помиловать
  • -
+
+
+

Simple list example

+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
+
+
+
new Sortable(example1, {
+    animation: 150,
+    ghostClass: 'blue-background-class'
+});
+
-
- - - - -
-
-
Multi
- -
-
Group A
-
- -
+
+ +
+

Shared lists

+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
-
-
Group B
-
- -
+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
+
+
new Sortable(example2Left, {
+    group: 'shared', // set both lists to same group
+    animation: 150
+});
 
-			
-
Group C
-
- -
+new Sortable(example2Right, { + group: 'shared', + animation: 150 +});
-
-
+
+ +
+

Cloning

+

Try dragging from one list to another. The item you drag will be cloned and the clone will stay in the original list.

+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
+
+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
+
+
+
new Sortable(example3Left, {
+    group: {
+        name: 'shared',
+        pull: 'clone' // To clone: set pull to 'clone'
+    },
+    animation: 150
+});
 
-	
-	
-	
-
-
Editable list
+new Sortable(example3Right, { + group: { + name: 'shared', + pull: 'clone' + }, + animation: 150 +});
+
+
+
+ +
+

Disabling Sorting

+

Try sorting the list on the left. It is not possible because it has it's sort option set to false. However, you can still drag from the list on the left to the list on the right.

+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
+
-
-
    -
  • Оля
  • -
  • Владимир
  • -
  • Алина
  • -
+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
+
+
+
new Sortable(example4Left, {
+    group: {
+        name: 'shared',
+        pull: 'clone',
+        put: false // Do not allow items to be put into this list
+    },
+    animation: 150,
+    sort: false // To disable sorting: set sort to false
+});
 
-				
+new Sortable(example4Right, {
+    group: 'shared',
+    animation: 150
+});
+
+
+
+ +
+

Handle

+
+
  Item 1
+
  Item 2
+
  Item 3
+
  Item 4
+
  Item 5
+
  Item 6
+
+
+
new Sortable(example5, {
+    handle: '.handle', // handle's class
+    animation: 150
+});
+
+
+
+ +
+

Filter

+

Try dragging the item with a red background. It cannot be done, because that item is filtered out using the filter option.

+
+
Item 1
+
Item 2
+
Item 3
+
Filtered
+
Item 4
+
Item 5
+
+
+
new Sortable(example6, {
+    filter: '.filtered', // 'filtered' class is not draggable
+    animation: 150
+});
+
+
+
+ +
+

Thresholds

+

Try modifying the inputs below to affect the swap thresholds. You can see the swap zones of the squares colored in dark blue, while the "dead zones" (that do not cause a swap) are colored in light blue.

+
+
+ +
+ +
1
+
+ +
+ +
2
+
+
+
+
+
+ +
+ +
+
+
+
Invert Swap
+
+
+ +
+
+
+
+ + +
+
+
+
+
new Sortable(example7, {
+    swapThreshold: 1,
+    animation: 150
+});
-
- - - -
-
-
Advanced groups
-
-
pull & put
-
    -
  • Meat
  • -
  • Potato
  • -
  • Tea
  • -
+
+

Examples

+
+
+ +
+

Grid Example

+
+
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6
Item 7
Item 8
Item 9
Item 10
Item 11
Item 12
Item 13
Item 14
Item 15
Item 16
Item 17
Item 18
Item 19
Item 20
- -
-
only pull (clone) no reordering
-
    -
  • Sex
  • -
  • Drugs
  • -
  • Rock'n'roll
  • -
+
+
+ +
+

Nested Sortables Example

+

NOTE: When using nested Sortables with animation, it is recommended that the fallbackOnBody option is set to true.
It is also always recommended that either the invertSwap option is set to true, or the swapThreshold option is lower than the default value of 1 (eg 0.65).

+
+
Item 1.1 +
+
Item 2.1
+
Item 2.2 +
+
Item 3.1
+
Item 3.2
+
Item 3.3
+
Item 3.4
+
+
+
Item 2.3
+
Item 2.4
+
+
+
Item 1.2
+
Item 1.3
+
Item 1.4 +
+
Item 2.1
+
Item 2.2
+
Item 2.3
+
Item 2.4
+
+
+
Item 1.5
- -
-
only put
-
    -
  • Money
  • -
  • Force
  • -
  • Agility
  • -
+
+
// Loop through each nested sortable element
+for (var i = 0; i < nestedSortables.length; i++) {
+	new Sortable(nestedSortables[i], {
+		group: 'nested',
+		animation: 150,
+		fallbackOnBody: true,
+		swapThreshold: 0.65
+	});
+}
+
-
+
+

Plugins

-
+
+ +
+

MultiDrag

+

The MultiDrag plugin allows for multiple items to be dragged at a time. You can click to "select" multiple items, and then drag them as one item.

+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
+
+
+
new Sortable(multiDragDemo, {
+	multiDrag: true, // Enable multi-drag
+	selectedClass: 'selected', // The class applied to the selected items
+	fallbackTolerance: 3, // So that we can select items on mobile
+	animation: 150
+});
+
+
+
+ +
+

Swap

+

The Swap plugin changes the behaviour of Sortable to allow for items to be swapped with eachother rather than sorted.

+
+
Item 1
+
Item 2
+
Item 3
+
Item 4
+
Item 5
+
Item 6
+
+
+
new Sortable(swapDemo, {
+	swap: true, // Enable swap plugin
+	swapClass: 'highlight', // The class applied to the hovered swap item
+	animation: 150
+});
+
+
+
- - -
-
-
Drag handle and selectable text
-
-
    -
  • Select text freely
  • -
  • Drag my handle
  • -
  • Best of both worlds
  • -
-
+
-
+
+

Comparisons

-
+
- - -
-
-
AngularJS / ng-sortable
- -
-
- {{remaining()}} of {{todos.length}} remaining - [ archive ] -
    -
  • - - {{todo.text}} -
  • -
-
- -
-
-
- - -
-
- {{remaining()}} of {{todos.length}} remaining -
    -
  • - - {{todo.text}} -
  • -
-
-
+
+

jQuery-UI

+ -
+

Dragula

+
-
+
- - -
-
-
Code example
-
// Simple list
-var list = document.getElementById("my-ui-list");
-Sortable.create(list); // That's all.
+		
+

Framework Support

+
+
+
-// Grouping -var foo = document.getElementById("foo"); -Sortable.create(foo, { group: "omega" }); +

Vue

+

Vue.Draggable

-var bar = document.getElementById("bar"); -Sortable.create(bar, { group: "omega" }); +

React

+

react-sortablejs

+

Angular

+

ngx-sortablejs

-// Or -var container = document.getElementById("multi"); -var sort = Sortable.create(container, { - animation: 150, // ms, animation speed moving items when sorting, `0` — without animation - handle: ".tile__title", // Restricts sort start click/touch to the specified element - draggable: ".tile", // Specifies which items inside the element should be sortable - onUpdate: function (evt/**Event*/){ - var item = evt.item; // the current dragged HTMLElement - } -}); +

jQuery

+

jquery-sortablejs

-// .. -sort.destroy(); +

Knockout

+

knockout-sortablejs

+

Meteor

+

meteor-sortablejs

-// Editable list -var editableList = Sortable.create(editable, { - filter: '.js-remove', - onFilter: function (evt) { - var el = editableList.closest(evt.item); // get dragged item - el && el.parentNode.removeChild(el); - } -}); -
-
+

Polymer

+

polymer-sortablejs

-
-
-
See also
-
Loading…
- -
+

Ember

+

ember-sortablejs

+ + - - - - + + - - - - - - - - - - diff --git a/jquery.binding.js b/jquery.binding.js deleted file mode 100644 index 16d7729b4..000000000 --- a/jquery.binding.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * jQuery plugin for Sortable - * @author RubaXa - * @license MIT - */ -(function (factory) { - "use strict"; - - if (typeof define === "function" && define.amd) { - define(["jquery"], factory); - } - else { - /* jshint sub:true */ - factory(jQuery); - } -})(function ($) { - "use strict"; - - - /* CODE */ - - - /** - * jQuery plugin for Sortable - * @param {Object|String} options - * @param {..*} [args] - * @returns {jQuery|*} - */ - $.fn.sortable = function (options) { - var retVal; - - this.each(function () { - var $el = $(this), - sortable = $el.data('sortable'); - - if (!sortable && (options instanceof Object || !options)) { - sortable = new Sortable(this, options); - $el.data('sortable', sortable); - } - - if (sortable) { - if (options === 'widget') { - return sortable; - } - else if (options === 'destroy') { - sortable.destroy(); - $el.removeData('sortable'); - } - else if (options in sortable) { - retVal = sortable[sortable].apply(sortable, [].slice.call(arguments, 1)); - } - } - }); - - return (retVal === void 0) ? this : retVal; - }; -}); diff --git a/knockout-sortable.js b/knockout-sortable.js deleted file mode 100644 index 6a7f70137..000000000 --- a/knockout-sortable.js +++ /dev/null @@ -1,161 +0,0 @@ -(function () { - "use strict"; - - var init = function (element, valueAccessor, allBindings, viewModel, bindingContext, sortableOptions) { - - var options = buildOptions(valueAccessor, sortableOptions); - - //It's seems that we cannot update the eventhandlers after we've created the sortable, so define them in init instead of update - ['onStart', 'onEnd', 'onRemove', 'onAdd', 'onUpdate', 'onSort', 'onFilter'].forEach(function (e) { - if (options[e] || eventHandlers[e]) - options[e] = function (eventType, parentVM, parentBindings, handler, e) { - var itemVM = ko.dataFor(e.item), - //All of the bindings on the parent element - bindings = ko.utils.peekObservable(parentBindings()), - //The binding options for the draggable/sortable binding of the parent element - bindingHandlerBinding = bindings.sortable || bindings.draggable, - //The collection that we should modify - collection = bindingHandlerBinding.collection || bindingHandlerBinding.foreach; - if (handler) - handler(e, itemVM, parentVM, collection, bindings); - if (eventHandlers[eventType]) - eventHandlers[eventType](e, itemVM, parentVM, collection, bindings); - }.bind(undefined, e, viewModel, allBindings, options[e]); - }); - - viewModel._sortable = Sortable.create(element, options); - - //Destroy the sortable if knockout disposes the element it's connected to - ko.utils.domNodeDisposal.addDisposeCallback(element, function () { - viewModel._sortable.destroy(); - }); - return ko.bindingHandlers.template.init(element, valueAccessor); - }, - update = function (element, valueAccessor, allBindings, viewModel, bindingContext, sortableOptions) { - - //There seems to be some problems with updating the options of a sortable - //Tested to change eventhandlers and the group options without any luck - - return ko.bindingHandlers.template.update(element, valueAccessor, allBindings, viewModel, bindingContext); - }, - eventHandlers = (function (handlers) { - - var moveOperations = [], - tryMoveOperation = function (e, itemVM, parentVM, collection, parentBindings) { - //A move operation is the combination of a add and remove event, this is to make sure that we have both the target and origin collections - var currentOperation = { event: e, itemVM: itemVM, parentVM: parentVM, collection: collection, parentBindings: parentBindings }, - existingOperation = moveOperations.filter(function (op) { - return op.itemVM === currentOperation.itemVM; - })[0]; - - if (!existingOperation) { - moveOperations.push(currentOperation); - } - else { - //We're finishing the operation and already have a handle on the operation item meaning that it's safe to remove it - moveOperations.splice(moveOperations.indexOf(existingOperation), 1); - - var removeOperation = currentOperation.event.type === 'remove' ? currentOperation : existingOperation, - addOperation = currentOperation.event.type === 'add' ? currentOperation : existingOperation; - - moveItem(itemVM, removeOperation.collection, addOperation.collection, addOperation.event.clone, addOperation.event); - } - }, - //Moves an item from the to (collection to from (collection), these can be references to the same collection which means it's a sort, - //clone indicates if we should move or copy the item into the new collection - moveItem = function (itemVM, from, to, clone, e) { - //Unwrapping this allows us to manipulate the actual array - var fromArray = from(), - //It's not certain that the items actual index is the same as the index reported by sortable due to filtering etc. - originalIndex = fromArray.indexOf(itemVM); - - //Remove sortables "unbound" element - e.item.parentNode.removeChild(e.item); - - //This splice is necessary for both clone and move/sort - //In sort/move since it shouldn't be at this index/in this array anymore - //In clone since we have to work around knockouts valuHasMutated when manipulating arrays and avoid a "unbound" item added by sortable - fromArray.splice(originalIndex, 1); - //Update the array, this will also remove sortables "unbound" clone - from.valueHasMutated(); - if (clone && from !== to) { - //Readd the item - fromArray.splice(originalIndex, 0, itemVM); - //Force knockout to update - from.valueHasMutated(); - } - //Insert the item on its new position - to().splice(e.newIndex, 0, itemVM); - //Make sure to tell knockout that we've modified the actual array. - to.valueHasMutated(); - }; - - handlers.onRemove = tryMoveOperation; - handlers.onAdd = tryMoveOperation; - handlers.onUpdate = function (e, itemVM, parentVM, collection, parentBindings) { - //This will be performed as a sort since the to/from collections reference the same collection and clone is set to false - moveItem(itemVM, collection, collection, false, e); - }; - - return handlers; - })({}), - //bindingOptions are the options set in the "data-bind" attribute in the ui. - //options are custom options, for instance draggable/sortable specific options - buildOptions = function (bindingOptions, options) { - //deep clone/copy of properties from the "from" argument onto the "into" argument and returns the modified "into" - var merge = function (into, from) { - for (var prop in from) { - if (Object.prototype.toString.call(from[prop]) === '[object Object]') { - if (Object.prototype.toString.call(into[prop]) !== '[object Object]') { - into[prop] = {}; - } - into[prop] = merge(into[prop], from[prop]); - } - else - into[prop] = from[prop]; - } - - return into; - }, - //unwrap the supplied options - unwrappedOptions = ko.utils.peekObservable(bindingOptions()).options || {}; - - //Make sure that we don't modify the provided settings object - options = merge({}, options); - - //group is handled differently since we should both allow to change a draggable to a sortable (and vice versa), - //but still be able to set a name on a draggable without it becoming a drop target. - if (unwrappedOptions.group && Object.prototype.toString.call(unwrappedOptions.group) !== '[object Object]') { - //group property is a name string declaration, convert to object. - unwrappedOptions.group = { name: unwrappedOptions.group }; - } - - return merge(options, unwrappedOptions); - }; - - ko.bindingHandlers.draggable = { - sortableOptions: { - group: { pull: 'clone', put: false }, - sort: false - }, - init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { - return init(element, valueAccessor, allBindings, viewModel, bindingContext, ko.bindingHandlers.draggable.sortableOptions); - }, - update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { - return update(element, valueAccessor, allBindings, viewModel, bindingContext, ko.bindingHandlers.draggable.sortableOptions); - } - }; - - ko.bindingHandlers.sortable = { - sortableOptions: { - group: { pull: true, put: true } - }, - init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { - return init(element, valueAccessor, allBindings, viewModel, bindingContext, ko.bindingHandlers.sortable.sortableOptions); - }, - update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { - return update(element, valueAccessor, allBindings, viewModel, bindingContext, ko.bindingHandlers.sortable.sortableOptions); - } - }; - -})(); \ No newline at end of file diff --git a/meteor/README.md b/meteor/README.md deleted file mode 100644 index c3403582e..000000000 --- a/meteor/README.md +++ /dev/null @@ -1,119 +0,0 @@ -Reactive reorderable lists with [Sortable](http://rubaxa.github.io/Sortable/), -backed by [Meteor.js](http://meteor.com) collections: - -* new elements arriving in the collection will update the list as you expect -* elements removed from the collection will be removed from the list -* drag and drop between lists updates collections accordingly - -Demo: http://rubaxa-sortable.meteor.com - -# Meteor - -If you're new to Meteor, here's what the excitement is all about - -[watch the first two minutes](https://www.youtube.com/watch?v=fsi0aJ9yr2o); you'll be hooked by 1:28. -That screencast is from 2012. In the meantime, Meteor has become a mature JavaScript-everywhere web -development framework. Read more at [Why Meteor](http://www.meteorpedia.com/read/Why_Meteor). - - -# Usage - -Simplest invocation - order will be lost when the page is refreshed: - -```handlebars -{{#sortable }} -``` - -Persist the sort order in the 'order' field of each document in the collection: - -*Client:* - -```handlebars -{{#sortable items= sortField="order"}} -``` - -*Server:* - -```js -Sortable.collections = ; // the name, not the variable -``` - -Along with `items`, `sortField` is the only Meteor-specific option. If it's missing, the package will -assume there is a field called "order" in the collection, holding unique `Number`s such that every -`order` differs from that before and after it by at least 1. Basically, keep to 0, 1, 2, ... . -Try not to depend on a particular format for this field; it *is* though guaranteed that a `sort` will -produce lexicographical order, and that the order will be maintained after an arbitrary number of -reorderings, unlike with [naive solutions](http://programmers.stackexchange.com/questions/266451/maintain-ordered-collection-by-updating-as-few-order-fields-as-possible). - -Remember to declare on the server which collections you want to be reorderable from the client. -Otherwise, the library will error because the client would be able to modify numerical fields in -any collection, which represents a security risk. - - -## Passing options to the Sortable library - - {{#sortable items= option1=value1 option2=value2...}} - {{#sortable items= options=myOptions}} - -For available options, please refer to [the main README](../README.md#options). You can pass them directly -or under the `options` object. Direct options (`key=value`) override those in `options`. It is best -to pass presentation-related options directly, and functionality-related settings in an `options` -object, as this will enable designers to work without needing to inspect the JavaScript code: - - - -Define the options in a helper for the template that calls Sortable: - -```js -Template.myTemplate.helpers({ - playerOptions: function () { - return { - group: { - name: "league", - pull: true, - put: false - }, - sort: false - }; - } -}); -``` - - -## Events - -All the original Sortable events are supported. In addition, they will receive -the data context in `event.data`. You can access `event.data.order` this way: - -```handlebars -{{#sortable items=players options=playersOptions}} -``` - -```js -Template.myTemplate.helpers({ - playersOptions: function () { - return { - onSort: function(/**Event*/event) { - console.log('Moved player #%d from %d to %d', - event.data.order, event.oldIndex, event.newIndex - ); - } - }; - } -}); -``` - - -# Issues - -If you encounter an issue while using this package, please CC @dandv when you file it in this repo. - - -# TODO - -* Array support -* Tests -* Misc. - see reactivize.js -* [GitHub issues](https://github.com/RubaXa/Sortable/labels/%E2%98%84%20meteor) diff --git a/meteor/example/.meteor/.finished-upgraders b/meteor/example/.meteor/.finished-upgraders deleted file mode 100644 index 8a761038c..000000000 --- a/meteor/example/.meteor/.finished-upgraders +++ /dev/null @@ -1,8 +0,0 @@ -# This file contains information which helps Meteor properly upgrade your -# app when you run 'meteor update'. You should check it into version control -# with your project. - -notices-for-0.9.0 -notices-for-0.9.1 -0.9.4-platform-file -notices-for-facebook-graph-api-2 diff --git a/meteor/example/.meteor/.gitignore b/meteor/example/.meteor/.gitignore deleted file mode 100644 index 408303742..000000000 --- a/meteor/example/.meteor/.gitignore +++ /dev/null @@ -1 +0,0 @@ -local diff --git a/meteor/example/.meteor/.id b/meteor/example/.meteor/.id deleted file mode 100644 index b39baa1d8..000000000 --- a/meteor/example/.meteor/.id +++ /dev/null @@ -1,7 +0,0 @@ -# This file contains a token that is unique to your project. -# Check it into your repository along with the rest of this directory. -# It can be used for purposes such as: -# - ensuring you don't accidentally deploy one app on top of another -# - providing package authors with aggregated statistics - -ir0jg2douy3yo5mehw diff --git a/meteor/example/.meteor/packages b/meteor/example/.meteor/packages deleted file mode 100644 index a33b0edfd..000000000 --- a/meteor/example/.meteor/packages +++ /dev/null @@ -1,12 +0,0 @@ -# Meteor packages used by this project, one per line. -# -# 'meteor add' and 'meteor remove' will edit this file for you, -# but you can also edit it by hand. - -meteor-platform -autopublish -insecure -rubaxa:sortable -dburles:mongo-collection-instances -fezvrasta:bootstrap-material-design -# twbs:bootstrap diff --git a/meteor/example/.meteor/platforms b/meteor/example/.meteor/platforms deleted file mode 100644 index 8a3a35f9f..000000000 --- a/meteor/example/.meteor/platforms +++ /dev/null @@ -1,2 +0,0 @@ -browser -server diff --git a/meteor/example/.meteor/release b/meteor/example/.meteor/release deleted file mode 100644 index dab6b552c..000000000 --- a/meteor/example/.meteor/release +++ /dev/null @@ -1 +0,0 @@ -METEOR@1.1.0.2 diff --git a/meteor/example/.meteor/versions b/meteor/example/.meteor/versions deleted file mode 100644 index abcbcf0a3..000000000 --- a/meteor/example/.meteor/versions +++ /dev/null @@ -1,53 +0,0 @@ -autopublish@1.0.3 -autoupdate@1.2.1 -base64@1.0.3 -binary-heap@1.0.3 -blaze@2.1.2 -blaze-tools@1.0.3 -boilerplate-generator@1.0.3 -callback-hook@1.0.3 -check@1.0.5 -dburles:mongo-collection-instances@0.3.3 -ddp@1.1.0 -deps@1.0.7 -ejson@1.0.6 -fastclick@1.0.3 -fezvrasta:bootstrap-material-design@0.3.0 -geojson-utils@1.0.3 -html-tools@1.0.4 -htmljs@1.0.4 -http@1.1.0 -id-map@1.0.3 -insecure@1.0.3 -jquery@1.11.3_2 -json@1.0.3 -lai:collection-extensions@0.1.3 -launch-screen@1.0.2 -livedata@1.0.13 -logging@1.0.7 -meteor@1.1.6 -meteor-platform@1.2.2 -minifiers@1.1.5 -minimongo@1.0.8 -mobile-status-bar@1.0.3 -mongo@1.1.0 -observe-sequence@1.0.6 -ordered-dict@1.0.3 -random@1.0.3 -reactive-dict@1.1.0 -reactive-var@1.0.5 -reload@1.1.3 -retry@1.0.3 -routepolicy@1.0.5 -rubaxa:sortable@1.2.0 -session@1.1.0 -spacebars@1.0.6 -spacebars-compiler@1.0.6 -templating@1.1.1 -tracker@1.0.7 -twbs:bootstrap@3.3.4 -ui@1.0.6 -underscore@1.0.3 -url@1.0.4 -webapp@1.2.0 -webapp-hashing@1.0.3 diff --git a/meteor/example/README.md b/meteor/example/README.md deleted file mode 100644 index 51d154718..000000000 --- a/meteor/example/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# RubaXa:Sortable Meteor demo - -This demo showcases the two-way integration between the reorderable list -widget [Sortable](https://github.com/RubaXa/Sortable/) and Meteor.js. Meteor -Mongo collections are updated when items are added, removed or reordered, and -the order is persisted. - -It also shows list grouping and control over what lists can give or receive -elements. You can only drag elements from the list to the left onto the list -to the right. - -## Usage - -The example uses the local package from the checkout, so it needs to wire -up some files (`package.js` and `package.json`). This is done by the handy -run script: - -### Windows - - git clone https://github.com/RubaXa/Sortable.git - cd Sortable - git checkout dev - cd meteor\example - run.bat - -### Elsewhere - - git clone https://github.com/RubaXa/Sortable.git - cd Sortable - git checkout dev - meteor/example./run.sh - -## Prior art - -### Differential - -Differential wrote [a blog post on reorderable lists with -Meteor](http://differential.com/blog/sortable-lists-in-meteor-using-jquery-ui) and -[jQuery UI Sortable](http://jqueryui.com/sortable/). It served as inspiration -for integrating [rubaxa:sortable](rubaxa.github.io/Sortable/), -which uses the HTML5 native drag&drop API (not without [its -limitations](https://github.com/RubaXa/Sortable/issues/106)). -The reordering method used by the Differential example can lead to data loss -though, because it calculates the new order of a dropped element as the -arithmetic mean of the elements before and after it. This [runs into limitations -of floating point precision](http://programmers.stackexchange.com/questions/266451/maintain-ordered-collection-by-updating-as-few-order-fields-as-possible) -in JavaScript after <50 reorderings. - -### Todos animated - -http://todos-dnd-animated.meteor.com/ ([source](https://github.com/nleush/meteor-todos-sortable-animation)) -is based on old Meteor Blaze (back then Spark) API, and won't work with current versions. -It does showcase some neat features, such as animation when collection elements -are reordered by another client. It uses jQuery UI Sortable as well, which lacks -some features vs. rubaxa:Sortable, e.g. text selection within the item. - -## TODO - -* Animation -* Indication that an item is being edited diff --git a/meteor/example/client/define-object-type.css b/meteor/example/client/define-object-type.css deleted file mode 100644 index d67b4b1d7..000000000 --- a/meteor/example/client/define-object-type.css +++ /dev/null @@ -1,57 +0,0 @@ -.glyphicon { - vertical-align: baseline; - font-size: 80%; - margin-right: 0.5em; -} - -[class^="mdi-"], [class*=" mdi-"] { - vertical-align: baseline; - font-size: 90%; - margin-right: 0.4em; -} - -.list-pair { - display: flex; /* use the flexbox model */ - flex-direction: row; -} -.sortable { -/* font-size: 2em;*/ -} - -.sortable.source { - /*background: #9FA8DA;*/ - flex: 0 0 auto; - margin-right: 1em; - cursor: move; - cursor: -webkit-grabbing; -} - -.sortable.target { - /*background: #3F51B5;*/ - flex: 1 1 auto; - margin-left: 1em; -} - -.target .well { - -} - -.sortable-handle { - cursor: move; - cursor: -webkit-grabbing; -} -.sortable-handle.pull-right { - margin-top: 0.3em; -} - -.sortable-ghost { - opacity: 0.6; -} - -/* show the remove button on hover */ -.removable .close { - display: none; -} -.removable:hover .close { - display: block; -} diff --git a/meteor/example/client/define-object-type.html b/meteor/example/client/define-object-type.html deleted file mode 100644 index d852cbcb5..000000000 --- a/meteor/example/client/define-object-type.html +++ /dev/null @@ -1,94 +0,0 @@ - - Reactive RubaXa:Sortable for Meteor - - - - {{> navbar}} - -
- - - {{> typeDefinition}} -
- - - - - - - - \ No newline at end of file diff --git a/meteor/example/client/define-object-type.js b/meteor/example/client/define-object-type.js deleted file mode 100644 index ad2a19e2a..000000000 --- a/meteor/example/client/define-object-type.js +++ /dev/null @@ -1,101 +0,0 @@ -// Define an object type by dragging together attributes - -Template.typeDefinition.helpers({ - types: function () { - return Types.find({}, { sort: { order: 1 } }); - }, - typesOptions: { - sortField: 'order', // defaults to 'order' anyway - group: { - name: 'typeDefinition', - pull: 'clone', - put: false - }, - sort: false // don't allow reordering the types, just the attributes below - }, - - attributes: function () { - return Attributes.find({}, { - sort: { order: 1 }, - transform: function (doc) { - doc.icon = Types.findOne({name: doc.type}).icon; - return doc; - } - }); - }, - attributesOptions: { - group: { - name: 'typeDefinition', - put: true - }, - onAdd: function (event) { - delete event.data._id; // Generate a new id when inserting in the Attributes collection. Otherwise, if we add the same type twice, we'll get an error that the ids are not unique. - delete event.data.icon; - event.data.type = event.data.name; - event.data.name = 'Rename me (double click)' - }, - // event handler for reordering attributes - onSort: function (event) { - console.log('Item %s went from #%d to #%d', - event.data.name, event.oldIndex, event.newIndex - ); - } - } -}); - -Template.sortableItemTarget.events({ - 'dblclick .name': function (event, template) { - // Make the name editable. We should use an existing component, but it's - // in a sorry state - https://github.com/arillo/meteor-x-editable/issues/1 - var name = template.$('.name'); - var input = template.$('input'); - if (input.length) { // jQuery never returns null - http://stackoverflow.com/questions/920236/how-can-i-detect-if-a-selector-returns-null - input.show(); - } else { - input = $(''); - name.after(input); - } - name.hide(); - input.focus(); - }, - 'blur input[type=text]': function (event, template) { - // commit the change to the name, if any - var input = template.$('input'); - input.hide(); - template.$('.name').show(); - // TODO - what is the collection here? We'll hard-code for now. - // https://github.com/meteor/meteor/issues/3303 - if (this.name !== input.val() && this.name !== '') - Attributes.update(this._id, {$set: {name: input.val()}}); - }, - 'keydown input[type=text]': function (event, template) { - if (event.which === 27) { - // ESC - discard edits and keep existing value - template.$('input').val(this.name); - event.preventDefault(); - event.target.blur(); - } else if (event.which === 13) { - // ENTER - event.preventDefault(); - event.target.blur(); - } - } -}); - -// you can add events to all Sortable template instances -Template.sortable.events({ - 'click .close': function (event, template) { - // `this` is the data context set by the enclosing block helper (#each, here) - template.collection.remove(this._id); - // custom code, working on a specific collection - if (Attributes.find().count() === 0) { - Meteor.setTimeout(function () { - Attributes.insert({ - name: 'Not nice to delete the entire list! Add some attributes instead.', - type: 'String', - order: 0 - }) - }, 1000); - } - } -}); diff --git a/meteor/example/model.js b/meteor/example/model.js deleted file mode 100644 index 8ae88226a..000000000 --- a/meteor/example/model.js +++ /dev/null @@ -1,2 +0,0 @@ -Types = new Mongo.Collection('types'); -Attributes = new Mongo.Collection('attributes'); diff --git a/meteor/example/run.bat b/meteor/example/run.bat deleted file mode 100755 index a6d845af5..000000000 --- a/meteor/example/run.bat +++ /dev/null @@ -1,4 +0,0 @@ -mklink ..\..\package.js "meteor/package.js" -mklink package.json "../../package.json" -meteor run -del ..\..\package.js package.json diff --git a/meteor/example/run.sh b/meteor/example/run.sh deleted file mode 100755 index aab44abf2..000000000 --- a/meteor/example/run.sh +++ /dev/null @@ -1,15 +0,0 @@ -# sanity check: make sure we're in the root directory of the example -cd "$( dirname "$0" )" - -# delete temp files even if Ctrl+C is pressed -int_trap() { - echo "Cleaning up..." -} -trap int_trap INT - -ln -s "meteor/package.js" ../../package.js 2>/dev/null -ln -s "../../package.json" package.json 2>/dev/null - -meteor run "$@" - -rm ../../package.js package.json diff --git a/meteor/example/server/fixtures.js b/meteor/example/server/fixtures.js deleted file mode 100644 index 617acf948..000000000 --- a/meteor/example/server/fixtures.js +++ /dev/null @@ -1,75 +0,0 @@ -Meteor.startup(function () { - if (Types.find().count() === 0) { - [ - { - name: 'String', - icon: '' - }, - { - name: 'Text, multi-line', - icon: '' - }, - { - name: 'Category', - icon: '' - }, - { - name: 'Number', - icon: '' - }, - { - name: 'Date', - icon: '' - }, - { - name: 'Hyperlink', - icon: '' - }, - { - name: 'Image', - icon: '' - }, - { - name: 'Progress', - icon: '' - }, - { - name: 'Duration', - icon: '' - }, - { - name: 'Map address', - icon: '' - }, - { - name: 'Relationship', - icon: '' - } - ].forEach(function (type, i) { - Types.insert({ - name: type.name, - icon: type.icon, - order: i - }); - } - ); - console.log('Initialized attribute types.'); - } - - if (Attributes.find().count() === 0) { - [ - { name: 'Name', type: 'String' }, - { name: 'Created at', type: 'Date' }, - { name: 'Link', type: 'Hyperlink' }, - { name: 'Owner', type: 'Relationship' } - ].forEach(function (attribute, i) { - Attributes.insert({ - name: attribute.name, - type: attribute.type, - order: i - }); - } - ); - console.log('Created sample object type.'); - } -}); diff --git a/meteor/example/server/sortable-collections.js b/meteor/example/server/sortable-collections.js deleted file mode 100644 index 76069a592..000000000 --- a/meteor/example/server/sortable-collections.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -Sortable.collections = ['attributes']; diff --git a/meteor/methods-client.js b/meteor/methods-client.js deleted file mode 100644 index 52f4ebec2..000000000 --- a/meteor/methods-client.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -Meteor.methods({ - /** - * Update the sortField of documents with given ids in a collection, incrementing it by incDec - * @param {String} collectionName - name of the collection to update - * @param {String[]} ids - array of document ids - * @param {String} orderField - the name of the order field, usually "order" - * @param {Number} incDec - pass 1 or -1 - */ - 'rubaxa:sortable/collection-update': function (collectionName, ids, sortField, incDec) { - var selector = {_id: {$in: ids}}, modifier = {$inc: {}}; - modifier.$inc[sortField] = incDec; - Mongo.Collection.get(collectionName).update(selector, modifier, {multi: true}); - } -}); diff --git a/meteor/methods-server.js b/meteor/methods-server.js deleted file mode 100644 index 9598bfc99..000000000 --- a/meteor/methods-server.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -Sortable = {}; -Sortable.collections = []; // array of collection names that the client is allowed to reorder - -Meteor.methods({ - /** - * Update the sortField of documents with given ids in a collection, incrementing it by incDec - * @param {String} collectionName - name of the collection to update - * @param {String[]} ids - array of document ids - * @param {String} orderField - the name of the order field, usually "order" - * @param {Number} incDec - pass 1 or -1 - */ - 'rubaxa:sortable/collection-update': function (collectionName, ids, sortField, incDec) { - check(collectionName, String); - // don't allow the client to modify just any collection - if (!Sortable || !Array.isArray(Sortable.collections)) { - throw new Meteor.Error(500, 'Please define Sortable.collections'); - } - if (Sortable.collections.indexOf(collectionName) === -1) { - throw new Meteor.Error(403, 'Collection <' + collectionName + '> is not Sortable. Please add it to Sortable.collections in server code.'); - } - - check(ids, [String]); - check(sortField, String); - check(incDec, Number); - var selector = {_id: {$in: ids}}, modifier = {$inc: {}}; - modifier.$inc[sortField] = incDec; - Mongo.Collection.get(collectionName).update(selector, modifier, {multi: true}); - } -}); diff --git a/meteor/package.js b/meteor/package.js deleted file mode 100644 index 51bf04b14..000000000 --- a/meteor/package.js +++ /dev/null @@ -1,35 +0,0 @@ -// package metadata file for Meteor.js -'use strict'; - -var packageName = 'rubaxa:sortable'; // http://atmospherejs.com/rubaxa/sortable - -var packageJson = JSON.parse(Npm.require("fs").readFileSync('package.json')); - -Package.describe({ - name: packageName, - summary: 'Sortable: reactive minimalist reorderable drag-and-drop lists on modern browsers and touch devices', - version: packageJson.version, - git: 'https://github.com/RubaXa/Sortable.git', - documentation: 'meteor/README.md' -}); - -Package.onUse(function (api) { - api.versionsFrom(['METEOR@0.9.0', 'METEOR@1.0']); - api.use('templating', 'client'); - api.use('dburles:mongo-collection-instances@0.3.3'); // to watch collections getting created - api.export('Sortable'); // exported on the server too, as a global to hold the array of sortable collections (for security) - api.addFiles([ - 'Sortable.js', - 'meteor/template.html', // the HTML comes first, so reactivize.js can refer to the template in it - 'meteor/reactivize.js' - ], 'client'); - api.addFiles('meteor/methods-client.js', 'client'); - api.addFiles('meteor/methods-server.js', 'server'); -}); - -Package.onTest(function (api) { - api.use(packageName, 'client'); - api.use('tinytest', 'client'); - - api.addFiles('meteor/test.js', 'client'); -}); diff --git a/meteor/publish.sh b/meteor/publish.sh deleted file mode 100755 index 56cd665ef..000000000 --- a/meteor/publish.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/bash -# Publish package to Meteor's repository, Atmospherejs.com - -# Make sure Meteor is installed, per https://www.meteor.com/install. -# The curl'ed script is totally safe; takes 2 minutes to read its source and check. -type meteor >/dev/null 2>&1 || { curl https://install.meteor.com/ | sh; } - -# sanity check: make sure we're in the root directory of the checkout -cd "$( dirname "$0" )/.." - -ALL_EXIT_CODE=0 - -# test any package*.js packages we may have, e.g. package.js, package-compat.js -for PACKAGE_FILE in meteor/package*.js; do - - # Meteor expects package.js to be in the root directory of the checkout, so copy there our package file under that name, temporarily - cp $PACKAGE_FILE ./package.js - - # publish package, creating it if it's the first time we're publishing - PACKAGE_NAME=$(grep -i name package.js | head -1 | cut -d "'" -f 2) - - echo "Publishing $PACKAGE_NAME..." - - # Attempt to re-publish the package - the most common operation once the initial release has - # been made. If the package name was changed (rare), you'll have to pass the --create flag. - meteor publish "$@"; EXIT_CODE=$? - ALL_EXIT_CODE=$(( $ALL_EXIT_CODE + $EXIT_CODE )) - if (( $EXIT_CODE == 0 )); then - echo "Thanks for releasing a new version. You can see it at" - echo "https://atmospherejs.com/${PACKAGE_NAME/://}" - else - echo "We got an error. Please post it at https://github.com/raix/Meteor-community-discussions/issues/14" - fi - - # rm the temporary build files and package.js - rm -rf ".build.$PACKAGE_NAME" versions.json package.js - -done - -exit $ALL_EXIT_CODE diff --git a/meteor/reactivize.js b/meteor/reactivize.js deleted file mode 100644 index a068a5ebb..000000000 --- a/meteor/reactivize.js +++ /dev/null @@ -1,201 +0,0 @@ -/* -Make a Sortable reactive by binding it to a Mongo.Collection. -Calls `rubaxa:sortable/collection-update` on the server to update the sortField of affected records. - -TODO: - * supply consecutive values if the `order` field doesn't have any - * .get(DOMElement) - return the Sortable object of a DOMElement - * create a new _id automatically onAdd if the event.from list had pull: 'clone' - * support arrays - * sparse arrays - * tests - * drop onto existing empty lists - * insert back into lists emptied by dropping - * performance on dragging into long list at the beginning - * handle failures on Collection operations, e.g. add callback to .insert - * when adding elements, update ranks just for the half closer to the start/end of the list - * revisit http://programmers.stackexchange.com/questions/266451/maintain-ordered-collection-by-updating-as-few-order-fields-as-possible - * reproduce the insidious bug where the list isn't always sorted (fiddle with dragging #1 over #2, then back, then #N before #1) - - */ - -'use strict'; - -Template.sortable.created = function () { - var templateInstance = this; - // `this` is a template instance that can store properties of our choice - http://docs.meteor.com/#/full/template_inst - if (templateInstance.setupDone) return; // paranoid: only run setup once - // this.data is the data context - http://docs.meteor.com/#/full/template_data - // normalize all options into templateInstance.options, and remove them from .data - templateInstance.options = templateInstance.data.options || {}; - Object.keys(templateInstance.data).forEach(function (key) { - if (key === 'options' || key === 'items') return; - templateInstance.options[key] = templateInstance.data[key]; - delete templateInstance.data[key]; - }); - templateInstance.options.sortField = templateInstance.options.sortField || 'order'; - // We can get the collection via the .collection property of the cursor, but changes made that way - // will NOT be sent to the server - https://github.com/meteor/meteor/issues/3271#issuecomment-66656257 - // Thus we need to use dburles:mongo-collection-instances to get a *real* collection - if (templateInstance.data.items && templateInstance.data.items.collection) { - // cursor passed via items=; its .collection works client-only and has a .name property - templateInstance.collectionName = templateInstance.data.items.collection.name; - templateInstance.collection = Mongo.Collection.get(templateInstance.collectionName); - } else if (templateInstance.data.items) { - // collection passed via items=; does NOT have a .name property, but _name - templateInstance.collection = templateInstance.data.items; - templateInstance.collectionName = templateInstance.collection._name; - } else if (templateInstance.data.collection) { - // cursor passed directly - templateInstance.collectionName = templateInstance.data.collection.name; - templateInstance.collection = Mongo.Collection.get(templateInstance.collectionName); - } else { - templateInstance.collection = templateInstance.data; // collection passed directly - templateInstance.collectionName = templateInstance.collection._name; - } - - // TODO if (Array.isArray(templateInstance.collection)) - - // What if user filters some of the items in the cursor, instead of ordering the entire collection? - // Use case: reorder by preference movies of a given genre, a filter within all movies. - // A: Modify all intervening items **that are on the client**, to preserve the overall order - // TODO: update *all* orders via a server method that takes not ids, but start & end elements - mild security risk - delete templateInstance.data.options; - - /** - * When an element was moved, adjust its orders and possibly the order of - * other elements, so as to maintain a consistent and correct order. - * - * There are three approaches to this: - * 1) Using arbitrary precision arithmetic and setting only the order of the moved - * element to the average of the orders of the elements around it - - * http://programmers.stackexchange.com/questions/266451/maintain-ordered-collection-by-updating-as-few-order-fields-as-possible - * The downside is that the order field in the DB will increase by one byte every - * time an element is reordered. - * 2) Adjust the orders of the intervening items. This keeps the orders sane (integers) - * but is slower because we have to modify multiple documents. - * TODO: we may be able to update fewer records by only altering the - * order of the records between the newIndex/oldIndex and the start/end of the list. - * 3) Use regular precision arithmetic, but when the difference between the orders of the - * moved item and the one before/after it falls below a certain threshold, adjust - * the order of that other item, and cascade doing so up or down the list. - * This will keep the `order` field constant in size, and will only occasionally - * require updating the `order` of other records. - * - * For now, we use approach #2. - * - * @param {String} itemId - the _id of the item that was moved - * @param {Number} orderPrevItem - the order of the item before it, or null - * @param {Number} orderNextItem - the order of the item after it, or null - */ - templateInstance.adjustOrders = function adjustOrders(itemId, orderPrevItem, orderNextItem) { - var orderField = templateInstance.options.sortField; - var selector = {}, modifier = {$set: {}}; - var ids = []; - var startOrder = templateInstance.collection.findOne(itemId)[orderField]; - if (orderPrevItem !== null) { - // Element has a previous sibling, therefore it was moved down in the list. - // Decrease the order of intervening elements. - selector[orderField] = {$lte: orderPrevItem, $gt: startOrder}; - ids = _.pluck(templateInstance.collection.find(selector, {fields: {_id: 1}}).fetch(), '_id'); - Meteor.call('rubaxa:sortable/collection-update', templateInstance.collectionName, ids, orderField, -1); - - // Set the order of the dropped element to the order of its predecessor, whose order was decreased - modifier.$set[orderField] = orderPrevItem; - } else { - // element moved up the list, increase order of intervening elements - selector[orderField] = {$gte: orderNextItem, $lt: startOrder}; - ids = _.pluck(templateInstance.collection.find(selector, {fields: {_id: 1}}).fetch(), '_id'); - Meteor.call('rubaxa:sortable/collection-update', templateInstance.collectionName, ids, orderField, 1); - - // Set the order of the dropped element to the order of its successor, whose order was increased - modifier.$set[orderField] = orderNextItem; - } - templateInstance.collection.update(itemId, modifier); - }; - - templateInstance.setupDone = true; -}; - - -Template.sortable.rendered = function () { - var templateInstance = this; - var orderField = templateInstance.options.sortField; - - // sorting was changed within the list - var optionsOnUpdate = templateInstance.options.onUpdate; - templateInstance.options.onUpdate = function sortableUpdate(/**Event*/event) { - var itemEl = event.item; // dragged HTMLElement - event.data = Blaze.getData(itemEl); - if (event.newIndex < event.oldIndex) { - // Element moved up in the list. The dropped element has a next sibling for sure. - var orderNextItem = Blaze.getData(itemEl.nextElementSibling)[orderField]; - templateInstance.adjustOrders(event.data._id, null, orderNextItem); - } else if (event.newIndex > event.oldIndex) { - // Element moved down in the list. The dropped element has a previous sibling for sure. - var orderPrevItem = Blaze.getData(itemEl.previousElementSibling)[orderField]; - templateInstance.adjustOrders(event.data._id, orderPrevItem, null); - } else { - // do nothing - drag and drop in the same location - } - if (optionsOnUpdate) optionsOnUpdate(event); - }; - - // element was added from another list - var optionsOnAdd = templateInstance.options.onAdd; - templateInstance.options.onAdd = function sortableAdd(/**Event*/event) { - var itemEl = event.item; // dragged HTMLElement - event.data = Blaze.getData(itemEl); - // let the user decorate the object with additional properties before insertion - if (optionsOnAdd) optionsOnAdd(event); - - // Insert the new element at the end of the list and move it where it was dropped. - // We could insert it at the beginning, but that would lead to negative orders. - var sortSpecifier = {}; sortSpecifier[orderField] = -1; - event.data.order = templateInstance.collection.findOne({}, { sort: sortSpecifier, limit: 1 }).order + 1; - // TODO: this can obviously be optimized by setting the order directly as the arithmetic average, with the caveats described above - var newElementId = templateInstance.collection.insert(event.data); - event.data._id = newElementId; - if (itemEl.nextElementSibling) { - var orderNextItem = Blaze.getData(itemEl.nextElementSibling)[orderField]; - templateInstance.adjustOrders(newElementId, null, orderNextItem); - } else { - // do nothing - inserted after the last element - } - // remove the dropped HTMLElement from the list because we have inserted it in the collection, which will update the template - itemEl.parentElement.removeChild(itemEl); - }; - - // element was removed by dragging into another list - var optionsOnRemove = templateInstance.options.onRemove; - templateInstance.options.onRemove = function sortableRemove(/**Event*/event) { - var itemEl = event.item; // dragged HTMLElement - event.data = Blaze.getData(itemEl); - // don't remove from the collection if group.pull is clone or false - if (typeof templateInstance.options.group === 'undefined' - || typeof templateInstance.options.group.pull === 'undefined' - || templateInstance.options.group.pull === true - ) templateInstance.collection.remove(event.data._id); - if (optionsOnRemove) optionsOnRemove(event); - }; - - // just compute the `data` context - ['onStart', 'onEnd', 'onSort', 'onFilter'].forEach(function (eventHandler) { - if (templateInstance.options[eventHandler]) { - var userEventHandler = templateInstance.options[eventHandler]; - templateInstance.options[eventHandler] = function (/**Event*/event) { - var itemEl = event.item; // dragged HTMLElement - event.data = Blaze.getData(itemEl); - userEventHandler(event); - }; - } - }); - - templateInstance.sortable = Sortable.create(templateInstance.firstNode.parentElement, templateInstance.options); - // TODO make the object accessible, e.g. via Sortable.getSortableById() or some such -}; - - -Template.sortable.destroyed = function () { - this.sortable.destroy(); -}; diff --git a/meteor/runtests.sh b/meteor/runtests.sh deleted file mode 100755 index 94aaecf05..000000000 --- a/meteor/runtests.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/bin/sh -# Test Meteor package before publishing to Atmospherejs.com - -# Make sure Meteor is installed, per https://www.meteor.com/install. -# The curl'ed script is totally safe; takes 2 minutes to read its source and check. -type meteor >/dev/null 2>&1 || { curl https://install.meteor.com/ | sh; } - -# sanity check: make sure we're in the root directory of the checkout -cd "$( dirname "$0" )/.." - - -# delete the temporary files even if Ctrl+C is pressed -int_trap() { - printf "\nTests interrupted. Cleaning up...\n\n" -} -trap int_trap INT - - -ALL_EXIT_CODE=0 - -# test any package*.js packages we may have, e.g. package.js, package-standalone.js -for PACKAGE_FILE in meteor/package*.js; do - - # Meteor expects package.js in the root dir of the checkout, so copy there our package file under that name, temporarily - cp $PACKAGE_FILE ./package.js - - PACKAGE_NAME=$(grep -i name package.js | head -1 | cut -d "'" -f 2) - - echo "### Testing $PACKAGE_NAME..." - - # provide an invalid MONGO_URL so Meteor doesn't bog us down with an empty Mongo database - if [ $# -gt 0 ]; then - # interpret any parameter to mean we want an interactive test - MONGO_URL=mongodb:// meteor test-packages ./ - else - # automated/CI test with phantomjs - ./node_modules/.bin/spacejam --mongo-url mongodb:// test-packages ./ - ALL_EXIT_CODES=$(( $ALL_EXIT_CODES + $? )) - fi - - # delete temporary build files and package.js - rm -rf .build.* versions.json package.js - -done - -exit $ALL_EXIT_CODES diff --git a/meteor/template.html b/meteor/template.html deleted file mode 100644 index 3923d3d9c..000000000 --- a/meteor/template.html +++ /dev/null @@ -1,5 +0,0 @@ - diff --git a/meteor/test.js b/meteor/test.js deleted file mode 100644 index f7c00a9fb..000000000 --- a/meteor/test.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -Tinytest.add('Sortable.is', function (test) { - var items = document.createElement('ul'); - items.innerHTML = '
  • item 1
  • item 2
  • item 3
  • '; - var sortable = new Sortable(items); - test.instanceOf(sortable, Sortable, 'Instantiation OK'); - test.length(sortable.toArray(), 3, 'Three elements'); -}); diff --git a/ng-sortable.js b/ng-sortable.js deleted file mode 100644 index 4f0b8c58f..000000000 --- a/ng-sortable.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * @author RubaXa - * @licence MIT - */ -(function (factory) { - 'use strict'; - - if (window.angular && window.Sortable) { - factory(angular, Sortable); - } - else if (typeof define === 'function' && define.amd) { - define(['angular', './Sortable'], factory); - } -})(function (angular, Sortable) { - 'use strict'; - - - /** - * @typedef {Object} ngSortEvent - * @property {*} model List item - * @property {Object|Array} models List of items - * @property {number} oldIndex before sort - * @property {number} newIndex after sort - */ - - - angular.module('ng-sortable', []) - .constant('ngSortableVersion', '0.3.7') - .constant('ngSortableConfig', {}) - .directive('ngSortable', ['$parse', 'ngSortableConfig', function ($parse, ngSortableConfig) { - var removed, - nextSibling; - - function getSource(el) { - var scope = angular.element(el).scope(); - var ngRepeat = [].filter.call(el.childNodes, function (node) { - return ( - (node.nodeType === 8) && - (node.nodeValue.indexOf('ngRepeat:') !== -1) - ); - })[0]; - - if (!ngRepeat) { - // Without ng-repeat - return null; - } - - // tests: http://jsbin.com/kosubutilo/1/edit?js,output - ngRepeat = ngRepeat.nodeValue.match(/ngRepeat:\s*(?:\(.*?,\s*)?([^\s)]+)[\s)]+in\s+([^\s|]+)/); - - var itemExpr = $parse(ngRepeat[1]); - var itemsExpr = $parse(ngRepeat[2]); - - return { - item: function (el) { - return itemExpr(angular.element(el).scope()); - }, - items: function () { - return itemsExpr(scope); - } - }; - } - - - // Export - return { - restrict: 'AC', - scope: { ngSortable: "=?" }, - link: function (scope, $el, attrs) { - var el = $el[0], - options = angular.extend(scope.ngSortable || {}, ngSortableConfig), - source = getSource(el), - watchers = [], - sortable - ; - - - function _emitEvent(/**Event*/evt, /*Mixed*/item) { - var name = 'on' + evt.type.charAt(0).toUpperCase() + evt.type.substr(1); - - /* jshint expr:true */ - options[name] && options[name]({ - model: item || source && source.item(evt.item), - models: source && source.items(), - oldIndex: evt.oldIndex, - newIndex: evt.newIndex - }); - } - - - function _sync(/**Event*/evt) { - if (!source) { - // Without ng-repeat - return; - } - - var oldIndex = evt.oldIndex, - newIndex = evt.newIndex, - items = source.items(); - - if (el !== evt.from) { - var prevSource = getSource(evt.from), - prevItems = prevSource.items(); - - oldIndex = prevItems.indexOf(prevSource.item(evt.item)); - removed = prevItems[oldIndex]; - - if (evt.clone) { - evt.from.removeChild(evt.clone); - removed = angular.copy(removed); - } - else { - prevItems.splice(oldIndex, 1); - } - - items.splice(newIndex, 0, removed); - - evt.from.insertBefore(evt.item, nextSibling); // revert element - } - else { - items.splice(newIndex, 0, items.splice(oldIndex, 1)[0]); - } - - scope.$apply(); - } - - - sortable = Sortable.create(el, Object.keys(options).reduce(function (opts, name) { - opts[name] = opts[name] || options[name]; - return opts; - }, { - onStart: function (/**Event*/evt) { - nextSibling = evt.item.nextSibling; - _emitEvent(evt); - scope.$apply(); - }, - onEnd: function (/**Event*/evt) { - _emitEvent(evt, removed); - scope.$apply(); - }, - onAdd: function (/**Event*/evt) { - _sync(evt); - _emitEvent(evt, removed); - scope.$apply(); - }, - onUpdate: function (/**Event*/evt) { - _sync(evt); - _emitEvent(evt); - }, - onRemove: function (/**Event*/evt) { - _emitEvent(evt, removed); - }, - onSort: function (/**Event*/evt) { - _emitEvent(evt); - } - })); - - $el.on('$destroy', function () { - angular.forEach(watchers, function (/** Function */unwatch) { - unwatch(); - }); - sortable.destroy(); - watchers = null; - sortable = null; - nextSibling = null; - }); - - angular.forEach([ - 'sort', 'disabled', 'draggable', 'handle', 'animation', - 'onStart', 'onEnd', 'onAdd', 'onUpdate', 'onRemove', 'onSort' - ], function (name) { - watchers.push(scope.$watch('ngSortable.' + name, function (value) { - if (value !== void 0) { - options[name] = value; - - if (!/^on[A-Z]/.test(name)) { - sortable.option(name, value); - } - } - })); - }); - } - }; - }]); -}); diff --git a/package.json b/package.json deleted file mode 100644 index 2a1c170af..000000000 --- a/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "sortablejs", - "exportName": "Sortable", - "version": "1.2.1", - "devDependencies": { - "grunt": "*", - "grunt-version": "*", - "grunt-exec": "*", - "grunt-contrib-jshint": "0.9.2", - "grunt-contrib-uglify": "*", - "spacejam": "*" - }, - "description": "Minimalist JavaScript library for reorderable drag-and-drop lists on modern browsers and touch devices. No jQuery. Supports AngularJS and any CSS library, e.g. Bootstrap.", - "main": "Sortable.js", - "scripts": { - "test": "grunt" - }, - "repository": { - "type": "git", - "url": "git://github.com/rubaxa/Sortable.git" - }, - "keywords": [ - "sortable", - "reorder", - "drag", - "meteor", - "angular", - "ng-sortable", - "react", - "mixin" - ], - "author": "Konstantin Lebedev ", - "license": "MIT", - "spm": { - "main": "Sortable.js", - "ignore": [ - "meteor", - "st" - ] - } -} diff --git a/react-sortable-mixin.js b/react-sortable-mixin.js deleted file mode 100644 index 56ae93da7..000000000 --- a/react-sortable-mixin.js +++ /dev/null @@ -1,157 +0,0 @@ -/** - * @author RubaXa - * @licence MIT - */ - -(function (factory) { - 'use strict'; - - if (typeof module != 'undefined' && typeof module.exports != 'undefined') { - module.exports = factory(require('./Sortable')); - } - else if (typeof define === 'function' && define.amd) { - define(['./Sortable'], factory); - } - else { - /* jshint sub:true */ - window['SortableMixin'] = factory(Sortable); - } -})(function (/** Sortable */Sortable) { - 'use strict'; - - var _nextSibling; - - var _activeComponent; - - var _defaultOptions = { - ref: 'list', - model: 'items', - - animation: 100, - onStart: 'handleStart', - onEnd: 'handleEnd', - onAdd: 'handleAdd', - onUpdate: 'handleUpdate', - onRemove: 'handleRemove', - onSort: 'handleSort', - onFilter: 'handleFilter' - }; - - - function _getModelName(component) { - return component.sortableOptions && component.sortableOptions.model || _defaultOptions.model; - } - - - function _getModelItems(component) { - var name = _getModelName(component), - items = component.state && component.state[name] || component.props[name]; - - return items.slice(); - } - - - function _extend(dst, src) { - for (var key in src) { - if (src.hasOwnProperty(key)) { - dst[key] = src[key]; - } - } - - return dst; - } - - - /** - * Simple and easy mixin-wrapper for rubaxa/Sortable library, in order to - * make reorderable drag-and-drop lists on modern browsers and touch devices. - * - * @mixin - */ - var SortableMixin = { - sortableMixinVersion: '0.1.0', - - - /** - * @type {Sortable} - * @private - */ - _sortableInstance: null, - - - componentDidMount: function () { - var options = _extend(_extend({}, _defaultOptions), this.sortableOptions || {}), - copyOptions = _extend({}, options), - - emitEvent = function (/** string */type, /** Event */evt) { - var method = this[options[type]]; - method && method.call(this, evt, this._sortableInstance); - }.bind(this); - - - // Bind callbacks so that "this" refers to the component - 'onStart onEnd onAdd onSort onUpdate onRemove onFilter'.split(' ').forEach(function (/** string */name) { - copyOptions[name] = function (evt) { - if (name === 'onStart') { - _nextSibling = evt.item.nextElementSibling; - _activeComponent = this; - } - else if (name === 'onAdd' || name === 'onUpdate') { - evt.from.insertBefore(evt.item, _nextSibling); - - var newState = {}, - remoteState = {}, - oldIndex = evt.oldIndex, - newIndex = evt.newIndex, - items = _getModelItems(this), - remoteItems, - item; - - if (name === 'onAdd') { - remoteItems = _getModelItems(_activeComponent); - item = remoteItems.splice(oldIndex, 1)[0]; - items.splice(newIndex, 0, item); - - remoteState[_getModelName(_activeComponent)] = remoteItems; - } - else { - items.splice(newIndex, 0, items.splice(oldIndex, 1)[0]); - } - - newState[_getModelName(this)] = items; - this.setState(newState); - (this !== _activeComponent) && _activeComponent.setState(remoteState); - } - - setTimeout(function () { - emitEvent(name, evt); - }, 0); - }.bind(this); - }, this); - - - /** @namespace this.refs — http://facebook.github.io/react/docs/more-about-refs.html */ - this._sortableInstance = Sortable.create((this.refs[options.ref] || this).getDOMNode(), copyOptions); - }, - - componentWillReceiveProps: function (nextProps) { - var newState = {}, - modelName = _getModelName(this), - items = nextProps[modelName]; - - if (items) { - newState[modelName] = items; - this.setState(newState); - } - }, - - componentWillUnmount: function () { - this._sortableInstance.destroy(); - this._sortableInstance = null; - } - }; - - - // Export - return SortableMixin; -}); diff --git a/st/app.css b/st/app.css deleted file mode 100644 index 6a97f8e49..000000000 --- a/st/app.css +++ /dev/null @@ -1,239 +0,0 @@ -html { - background-image: -webkit-linear-gradient(bottom, #F4E2C9 20%, #F4D7C9 100%); - background-image: -ms-linear-gradient(bottom, #F4E2C9 20%, #F4D7C9 100%); - background-image: linear-gradient(to bottom, #F4E2C9 20%, #F4D7C9 100%); -} - -html, body { - margin: 0; - padding: 0; - position: relative; - color: #464637; - min-height: 100%; - font-size: 20px; - font-family: 'Roboto', sans-serif; - font-weight: 300; -} - - -h1 { - color: #FF3F00; - font-size: 20px; - font-family: 'Roboto', sans-serif; - font-weight: 300; - text-align: center; -} - - -ul { - margin: 0; - padding: 0; - list-style: none; -} - -.container { - width: 80%; - margin: auto; - min-width: 1100px; - max-width: 1300px; - position: relative; -} - -@media (min-width: 750px) and (max-width: 970px){ - .container { - width: 100%; - min-width: 750px; - } -} - - -.sortable-ghost { - opacity: .2; -} - - -img { - border: 0; - vertical-align: middle; -} - - -.logo { - top: 55px; - left: 30px; - position: absolute; -} - - -.title { - color: #fff; - padding: 3px 10px; - display: inline-block; - position: relative; - background-color: #FF7373; - z-index: 1000; -} - .title_xl { - padding: 3px 15px; - font-size: 40px; - } - - - -.tile { - width: 22%; - min-width: 245px; - color: #FF7270; - padding: 10px 30px; - text-align: center; - margin-top: 15px; - margin-left: 5px; - margin-right: 30px; - background-color: #fff; - display: inline-block; - vertical-align: top; -} - .tile__name { - cursor: move; - padding-bottom: 10px; - border-bottom: 1px solid #FF7373; - } - - .tile__list { - margin-top: 10px; - } - .tile__list:last-child { - margin-right: 0; - min-height: 80px; - } - - .tile__list img { - cursor: move; - margin: 10px; - border-radius: 100%; - } - - - -.block { - opacity: 1; - position: absolute; -} - .block__list { - padding: 20px 0; - max-width: 360px; - margin-top: -8px; - margin-left: 5px; - background-color: #fff; - } - .block__list-title { - margin: -20px 0 0; - padding: 10px; - text-align: center; - background: #5F9EDF; - } - .block__list li { cursor: move; } - - .block__list_words li { - background-color: #fff; - padding: 10px 40px; - } - .block__list_words .sortable-ghost { - opacity: 0.4; - background-color: #F4E2C9; - } - - .block__list_words li:first-letter { - text-transform: uppercase; - } - - .block__list_tags { - padding-left: 30px; - } - - .block__list_tags:after { - clear: both; - content: ''; - display: block; - } - .block__list_tags li { - color: #fff; - float: left; - margin: 8px 20px 10px 0; - padding: 5px 10px; - min-width: 10px; - background-color: #5F9EDF; - text-align: center; - } - .block__list_tags li:first-child:first-letter { - text-transform: uppercase; - } - - - -#editable {} - #editable li { - position: relative; - } - - #editable i { - -webkit-transition: opacity .2s; - transition: opacity .2s; - opacity: 0; - display: block; - cursor: pointer; - color: #c00; - top: 10px; - right: 40px; - position: absolute; - font-style: normal; - } - - #editable li:hover i { - opacity: 1; - } - - -#filter {} - #filter button { - color: #fff; - width: 100%; - border: none; - outline: 0; - opacity: .5; - margin: 10px 0 0; - transition: opacity .1s ease; - cursor: pointer; - background: #5F9EDF; - padding: 10px 0; - font-size: 20px; - } - #filter button:hover { - opacity: 1; - } - - #filter .block__list { - padding-bottom: 0; - } - -.drag-handle { - margin-right: 10px; - font: bold 20px Sans-Serif; - color: #5F9EDF; - display: inline-block; - cursor: move; - cursor: -webkit-grabbing; /* overrides 'move' */ -} - -#todos input { - padding: 5px; - font-size: 14px; - font-family: 'Roboto', sans-serif; - font-weight: 300; -} - - - -#nested ul li { - background-color: rgba(0,0,0,.05); -} diff --git a/st/app.js b/st/app.js index 164270d9a..7316b90e7 100644 --- a/st/app.js +++ b/st/app.js @@ -1,226 +1,223 @@ -(function () { - 'use strict'; +var example1 = document.getElementById('example1'), + example2Left = document.getElementById('example2-left'), + example2Right = document.getElementById('example2-right'), + example3Left = document.getElementById('example3-left'), + example3Right = document.getElementById('example3-right'), + example4Left = document.getElementById('example4-left'), + example4Right = document.getElementById('example4-right'), + example5 = document.getElementById('example5'), + example6 = document.getElementById('example6'), + example7 = document.getElementById('example7'), + gridDemo = document.getElementById('gridDemo'), + multiDragDemo = document.getElementById('multiDragDemo'), + swapDemo = document.getElementById('swapDemo'); + +// Example 1 - Simple list +new Sortable(example1, { + animation: 150, + ghostClass: 'blue-background-class' +}); + + +// Example 2 - Shared lists +new Sortable(example2Left, { + group: 'shared', // set both lists to same group + animation: 150 +}); + +new Sortable(example2Right, { + group: 'shared', + animation: 150 +}); + +// Example 3 - Cloning +new Sortable(example3Left, { + group: { + name: 'shared', + pull: 'clone' // To clone: set pull to 'clone' + }, + animation: 150 +}); - var byId = function (id) { return document.getElementById(id); }, +new Sortable(example3Right, { + group: { + name: 'shared', + pull: 'clone' + }, + animation: 150 +}); - loadScripts = function (desc, callback) { - var deps = [], key, idx = 0; - for (key in desc) { - deps.push(key); - } +// Example 4 - No Sorting +new Sortable(example4Left, { + group: { + name: 'shared', + pull: 'clone', + put: false // Do not allow items to be put into this list + }, + animation: 150, + sort: false // To disable sorting: set sort to false +}); - (function _next() { - var pid, - name = deps[idx], - script = document.createElement('script'); +new Sortable(example4Right, { + group: 'shared', + animation: 150 +}); - script.type = 'text/javascript'; - script.src = desc[deps[idx]]; - pid = setInterval(function () { - if (window[name]) { - clearTimeout(pid); +// Example 5 - Handle +new Sortable(example5, { + handle: '.handle', // handle class + animation: 150 +}); - deps[idx++] = window[name]; +// Example 6 - Filter +new Sortable(example6, { + filter: '.filtered', + animation: 150 +}); - if (deps[idx]) { - _next(); - } else { - callback.apply(null, deps); - } - } - }, 30); +// Example 7 - Thresholds +var example7Sortable = new Sortable(example7, { + animation: 150 +}); - document.getElementsByTagName('head')[0].appendChild(script); - })() - }, - console = window.console; +var example7SwapThreshold = 1; +var example7SwapThresholdInput = document.getElementById('example7SwapThresholdInput'); +var example7SwapThresholdCode = document.getElementById('example7SwapThresholdCode'); +var example7SwapThresholdIndicators = [].slice.call(document.querySelectorAll('.swap-threshold-indicator')); +var example7InvertSwapInput = document.getElementById('example7InvertSwapInput'); +var example7InvertSwapCode = document.getElementById('example7InvertSwapCode'); +var example7InvertedSwapThresholdIndicators = [].slice.call(document.querySelectorAll('.inverted-swap-threshold-indicator')); - if (!console.log) { - console.log = function () { - alert([].join.apply(arguments, ' ')); - }; - } +var example7Squares = [].slice.call(document.querySelectorAll('.square')); +var activeIndicators = example7SwapThresholdIndicators; - Sortable.create(byId('foo'), { - group: "words", - animation: 150, - store: { - get: function (sortable) { - var order = localStorage.getItem(sortable.options.group); - return order ? order.split('|') : []; - }, - set: function (sortable) { - var order = sortable.toArray(); - localStorage.setItem(sortable.options.group, order.join('|')); - } - }, - onAdd: function (evt){ console.log('onAdd.foo:', [evt.item, evt.from]); }, - onUpdate: function (evt){ console.log('onUpdate.foo:', [evt.item, evt.from]); }, - onRemove: function (evt){ console.log('onRemove.foo:', [evt.item, evt.from]); }, - onStart:function(evt){ console.log('onStart.foo:', [evt.item, evt.from]);}, - onSort:function(evt){ console.log('onStart.foo:', [evt.item, evt.from]);}, - onEnd: function(evt){ console.log('onEnd.foo:', [evt.item, evt.from]);} - }); +var example7DirectionInput = document.getElementById('example7DirectionInput'); +var example7SizeProperty = 'width'; - Sortable.create(byId('bar'), { - group: "words", - animation: 150, - onAdd: function (evt){ console.log('onAdd.bar:', evt.item); }, - onUpdate: function (evt){ console.log('onUpdate.bar:', evt.item); }, - onRemove: function (evt){ console.log('onRemove.bar:', evt.item); }, - onStart:function(evt){ console.log('onStart.foo:', evt.item);}, - onEnd: function(evt){ console.log('onEnd.foo:', evt.item);} - }); +function renderThresholdWidth(evt) { + example7SwapThreshold = Number(evt.target.value); + example7SwapThresholdCode.innerHTML = evt.target.value.indexOf('.') > -1 ? evt.target.value.padEnd(4, '0') : evt.target.value; + for (var i = 0; i < activeIndicators.length; i++) { + activeIndicators[i].style[example7SizeProperty] = (evt.target.value * 100) / + (activeIndicators == example7SwapThresholdIndicators ? 1 : 2) + '%'; + } - // Multi groups - Sortable.create(byId('multi'), { - animation: 150, - draggable: '.tile', - handle: '.tile__name' - }); + example7Sortable.option('swapThreshold', example7SwapThreshold); +} - [].forEach.call(byId('multi').getElementsByClassName('tile__list'), function (el){ - Sortable.create(el, { - group: 'photo', - animation: 150 - }); - }); +example7SwapThresholdInput.addEventListener('input', renderThresholdWidth); +example7InvertSwapInput.addEventListener('input', function(evt) { + example7Sortable.option('invertSwap', evt.target.checked); - // Editable list - var editableList = Sortable.create(byId('editable'), { - animation: 150, - filter: '.js-remove', - onFilter: function (evt) { - evt.item.parentNode.removeChild(evt.item); - } - }); + for (var i = 0; i < activeIndicators.length; i++) { + activeIndicators[i].style.display = 'none'; + } - byId('addUser').onclick = function () { - Ply.dialog('prompt', { - title: 'Add', - form: { name: 'name' } - }).done(function (ui) { - var el = document.createElement('li'); - el.innerHTML = ui.data.name + ''; - editableList.el.appendChild(el); - }); - }; + if (evt.target.checked) { + example7InvertSwapCode.style.display = ''; - // Advanced groups - [{ - name: 'advanced', - pull: true, - put: true - }, - { - name: 'advanced', - pull: 'clone', - put: false - }, { - name: 'advanced', - pull: false, - put: true - }].forEach(function (groupOpts, i) { - Sortable.create(byId('advanced-' + (i + 1)), { - sort: (i != 1), - group: groupOpts, - animation: 150 - }); + activeIndicators = example7InvertedSwapThresholdIndicators; + } else { + example7InvertSwapCode.style.display = 'none'; + activeIndicators = example7SwapThresholdIndicators; + } + + renderThresholdWidth({ + target: example7SwapThresholdInput }); + for (i = 0; i < activeIndicators.length; i++) { + activeIndicators[i].style.display = ''; + } +}); - // 'handle' option - Sortable.create(byId('handle-1'), { - handle: '.drag-handle', - animation: 150 - }); +function renderDirection(evt) { + for (var i = 0; i < example7Squares.length; i++) { + example7Squares[i].style.display = evt.target.value === 'h' ? 'inline-block' : 'block'; + } + + for (i = 0; i < example7InvertedSwapThresholdIndicators.length; i++) { + /* jshint expr:true */ + evt.target.value === 'h' && (example7InvertedSwapThresholdIndicators[i].style.height = '100%'); + evt.target.value === 'v' && (example7InvertedSwapThresholdIndicators[i].style.width = '100%'); + } + + for (i = 0; i < example7SwapThresholdIndicators.length; i++) { + if (evt.target.value === 'h') { + example7SwapThresholdIndicators[i].style.height = '100%'; + example7SwapThresholdIndicators[i].style.marginLeft = '50%'; + example7SwapThresholdIndicators[i].style.transform = 'translateX(-50%)'; + example7SwapThresholdIndicators[i].style.marginTop = '0'; + } else { + example7SwapThresholdIndicators[i].style.width = '100%'; + example7SwapThresholdIndicators[i].style.marginTop = '50%'; + example7SwapThresholdIndicators[i].style.transform = 'translateY(-50%)'; - // Angular example - angular.module('todoApp', ['ng-sortable']) - .constant('ngSortableConfig', {onEnd: function() { - console.log('default onEnd()'); - }}) - .controller('TodoController', ['$scope', function ($scope) { - $scope.todos = [ - {text: 'learn angular', done: true}, - {text: 'build an angular app', done: false} - ]; - - $scope.addTodo = function () { - $scope.todos.push({text: $scope.todoText, done: false}); - $scope.todoText = ''; - }; - - $scope.remaining = function () { - var count = 0; - angular.forEach($scope.todos, function (todo) { - count += todo.done ? 0 : 1; - }); - return count; - }; - - $scope.archive = function () { - var oldTodos = $scope.todos; - $scope.todos = []; - angular.forEach(oldTodos, function (todo) { - if (!todo.done) $scope.todos.push(todo); - }); - }; - }]) - .controller('TodoControllerNext', ['$scope', function ($scope) { - $scope.todos = [ - {text: 'learn Sortable', done: true}, - {text: 'use ng-sortable', done: false}, - {text: 'Enjoy', done: false} - ]; - - $scope.remaining = function () { - var count = 0; - angular.forEach($scope.todos, function (todo) { - count += todo.done ? 0 : 1; - }); - return count; - }; - - $scope.sortableConfig = { group: 'todo', animation: 150 }; - 'Start End Add Update Remove Sort'.split(' ').forEach(function (name) { - $scope.sortableConfig['on' + name] = console.log.bind(console, name); - }); - }]); -})(); - - - -// Background -document.addEventListener("DOMContentLoaded", function () { - function setNoiseBackground(el, width, height, opacity) { - var canvas = document.createElement("canvas"); - var context = canvas.getContext("2d"); - - canvas.width = width; - canvas.height = height; - - for (var i = 0; i < width; i++) { - for (var j = 0; j < height; j++) { - var val = Math.floor(Math.random() * 255); - context.fillStyle = "rgba(" + val + "," + val + "," + val + "," + opacity + ")"; - context.fillRect(i, j, 1, 1); - } + example7SwapThresholdIndicators[i].style.marginLeft = '0'; } + } - el.style.background = "url(" + canvas.toDataURL("image/png") + ")"; + if (evt.target.value === 'h') { + example7SizeProperty = 'width'; + example7Sortable.option('direction', 'horizontal'); + } else { + example7SizeProperty = 'height'; + example7Sortable.option('direction', 'vertical'); } - setNoiseBackground(document.getElementsByTagName('body')[0], 50, 50, 0.02); -}, false); + renderThresholdWidth({ + target: example7SwapThresholdInput + }); +} +example7DirectionInput.addEventListener('input', renderDirection); + +renderDirection({ + target: example7DirectionInput +}); + + +// Grid demo +new Sortable(gridDemo, { + animation: 150, + ghostClass: 'blue-background-class' +}); + +// Nested demo +var nestedSortables = [].slice.call(document.querySelectorAll('.nested-sortable')); + +// Loop through each nested sortable element +for (var i = 0; i < nestedSortables.length; i++) { + new Sortable(nestedSortables[i], { + group: 'nested', + animation: 150, + fallbackOnBody: true, + swapThreshold: 0.65 + }); +} + +// MultiDrag demo +new Sortable(multiDragDemo, { + multiDrag: true, + selectedClass: 'selected', + fallbackTolerance: 3, // So that we can select items on mobile + animation: 150 +}); + + +// Swap demo +new Sortable(swapDemo, { + swap: true, + swapClass: 'highlight', + animation: 150 +}); diff --git a/st/carbon.css b/st/carbon.css new file mode 100644 index 000000000..d82803583 --- /dev/null +++ b/st/carbon.css @@ -0,0 +1,147 @@ +@media (min-width: 992px) { + #carbonads { + display: block; + overflow: hidden; + padding: 10px; + box-shadow: 0 1px 3px hsla(0, 0%, 0%, .05); + border-radius: 4px; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', Helvetica, Arial, sans-serif; + line-height: 1.5; + max-width: 300px; + margin-top: 50px; + font-size: 12px; + position: absolute; + background-color: #fff; + } + + #carbonads a { + text-decoration: none; + } + + #carbonads span { + position: relative; + display: block; + overflow: hidden; + } + + .carbon-img { + float: left; + margin-right: 1em; + } + + .carbon-img img { + display: block; + } + + .carbon-text { + display: block; + float: left; + max-width: calc(100% - 130px - 1em); + text-align: left; + color: #637381; + } + + .carbon-poweredby { + position: absolute; + left: 142px; + bottom: 0; + display: block; + font-size: 8px; + color: #c5cdd0; + font-weight: 500; + text-transform: uppercase; + line-height: 1; + letter-spacing: 1px; + } +} + +@media (max-width: 992px) { + #carbonads { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, + Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, + sans-serif; + --width: 728px; + --font-size: 22px; + } + + #carbonads { + display: block; + overflow: hidden; + max-width: var(--width); + position: relative; + background-color: hsl(0, 0%, 99%); + border: solid 1px #eee; + font-size: var(--font-size); + box-sizing: border-box; + } + + .detail #carbonads { + margin-top: 12px; + } + + #carbonads a { + color: inherit; + text-decoration: none; + } + + #carbonads a:hover { + color: inherit; + } + + .carbon-wrap { + display: flex; + align-items: center; + } + + carbon-img { + display: block; + float: left; + margin: 0; + max-width: var(--width); + line-height: 1; + } + + .carbon-img img { + display: block; + height: 90px; + width: auto; + } + + .carbon-text { + display: block; + float: left; + padding: 0 1em; + line-height: 1.35; + max-width: calc(100% - 130px - 2em); + text-align: left; + } + + .carbon-poweredby { + display: block; + position: absolute; + bottom: 0; + right: 0; + padding: 6px 10px; + background: repeating-linear-gradient( + -45deg, + transparent, + transparent 5px, + hsla(0, 0%, 0%, 0.025) 5px, + hsla(0, 0%, 0%, 0.025) 10px + ) + hsla(203, 11%, 95%, 0.8); + text-align: center; + text-transform: uppercase; + letter-spacing: 0.5px; + font-weight: 600; + font-size: 8px; + border-top-left-radius: 4px; + line-height: 1; + } + + @media only screen and (min-width: 320px) and (max-width: 759px) { + .carbon-text { + font-size: 14px; + } + } +} \ No newline at end of file diff --git a/st/face-01.jpg b/st/face-01.jpg deleted file mode 100644 index 06f9640b2..000000000 Binary files a/st/face-01.jpg and /dev/null differ diff --git a/st/face-02.jpg b/st/face-02.jpg deleted file mode 100644 index 9063724c8..000000000 Binary files a/st/face-02.jpg and /dev/null differ diff --git a/st/face-03.jpg b/st/face-03.jpg deleted file mode 100644 index 3e64a48bd..000000000 Binary files a/st/face-03.jpg and /dev/null differ diff --git a/st/face-04.jpg b/st/face-04.jpg deleted file mode 100644 index 0e5c73bcc..000000000 Binary files a/st/face-04.jpg and /dev/null differ diff --git a/st/face-05.jpg b/st/face-05.jpg deleted file mode 100644 index a8111224d..000000000 Binary files a/st/face-05.jpg and /dev/null differ diff --git a/st/face-06.jpg b/st/face-06.jpg deleted file mode 100644 index 063be7272..000000000 Binary files a/st/face-06.jpg and /dev/null differ diff --git a/st/face-07.jpg b/st/face-07.jpg deleted file mode 100644 index aebd0112e..000000000 Binary files a/st/face-07.jpg and /dev/null differ diff --git a/st/face-08.jpg b/st/face-08.jpg deleted file mode 100644 index b4e27f196..000000000 Binary files a/st/face-08.jpg and /dev/null differ diff --git a/st/face-09.jpg b/st/face-09.jpg deleted file mode 100644 index 8ecdef6e3..000000000 Binary files a/st/face-09.jpg and /dev/null differ diff --git a/st/prettify/prettify.css b/st/prettify/prettify.css new file mode 100644 index 000000000..e6fe342f2 --- /dev/null +++ b/st/prettify/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.clo,.opn,.pun{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.kwd,.tag,.typ{font-weight:700}.str{color:#060}.kwd{color:#006}.com{color:#600;font-style:italic}.typ{color:#404}.lit{color:#044}.clo,.opn,.pun{color:#440}.tag{color:#006}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} \ No newline at end of file diff --git a/st/prettify/prettify.js b/st/prettify/prettify.js new file mode 100644 index 000000000..477f03d55 --- /dev/null +++ b/st/prettify/prettify.js @@ -0,0 +1,46 @@ +!function(){/* + + Copyright (C) 2006 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +"undefined"!==typeof window&&(window.PR_SHOULD_USE_CONTINUATION=!0); +(function(){function T(a){function d(e){var a=e.charCodeAt(0);if(92!==a)return a;var c=e.charAt(1);return(a=w[c])?a:"0"<=c&&"7">=c?parseInt(e.substring(1),8):"u"===c||"x"===c?parseInt(e.substring(2),16):e.charCodeAt(1)}function f(e){if(32>e)return(16>e?"\\x0":"\\x")+e.toString(16);e=String.fromCharCode(e);return"\\"===e||"-"===e||"]"===e||"^"===e?"\\"+e:e}function c(e){var c=e.substring(1,e.length-1).match(RegExp("\\\\u[0-9A-Fa-f]{4}|\\\\x[0-9A-Fa-f]{2}|\\\\[0-3][0-7]{0,2}|\\\\[0-7]{1,2}|\\\\[\\s\\S]|-|[^-\\\\]","g")); +e=[];var a="^"===c[0],b=["["];a&&b.push("^");for(var a=a?1:0,g=c.length;ak||122k||90k||122h[0]&&(h[1]+1>h[0]&&b.push("-"),b.push(f(h[1])));b.push("]");return b.join("")}function m(e){for(var a=e.source.match(RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g")),b=a.length,d=[],g=0,h=0;g/,null])):d.push(["com",/^#[^\r\n]*/,null,"#"]));a.cStyleComments&&(f.push(["com",/^\/\/[^\r\n]*/,null]),f.push(["com",/^\/\*[\s\S]*?(?:\*\/|$)/,null]));if(c=a.regexLiterals){var m=(c=1|\\/=?|::?|<>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*("+ +("/(?=[^/*"+c+"])(?:[^/\\x5B\\x5C"+c+"]|\\x5C"+m+"|\\x5B(?:[^\\x5C\\x5D"+c+"]|\\x5C"+m+")*(?:\\x5D|$))+/")+")")])}(c=a.types)&&f.push(["typ",c]);c=(""+a.keywords).replace(/^ | $/g,"");c.length&&f.push(["kwd",new RegExp("^(?:"+c.replace(/[\s,]+/g,"|")+")\\b"),null]);d.push(["pln",/^\s+/,null," \r\n\t\u00a0"]);c="^.[^\\s\\w.$@'\"`/\\\\]*";a.regexLiterals&&(c+="(?!s*/)");f.push(["lit",/^@[a-z_$][a-z_$@0-9]*/i,null],["typ",/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],["pln",/^[a-z_$][a-z_$@0-9]*/i, +null],["lit",/^(?:0x[a-f0-9]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+\-]?\d+)?)[a-z]*/i,null,"0123456789"],["pln",/^\\[\s\S]?/,null],["pun",new RegExp(c),null]);return G(d,f)}function L(a,d,f){function c(a){var b=a.nodeType;if(1==b&&!t.test(a.className))if("br"===a.nodeName.toLowerCase())m(a),a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)c(a);else if((3==b||4==b)&&f){var e=a.nodeValue,d=e.match(q);d&&(b=e.substring(0,d.index),a.nodeValue=b,(e=e.substring(d.index+ +d[0].length))&&a.parentNode.insertBefore(l.createTextNode(e),a.nextSibling),m(a),b||a.parentNode.removeChild(a))}}function m(a){function c(a,b){var e=b?a.cloneNode(!1):a,k=a.parentNode;if(k){var k=c(k,1),d=a.nextSibling;k.appendChild(e);for(var f=d;f;f=d)d=f.nextSibling,k.appendChild(f)}return e}for(;!a.nextSibling;)if(a=a.parentNode,!a)return;a=c(a.nextSibling,0);for(var e;(e=a.parentNode)&&1===e.nodeType;)a=e;b.push(a)}for(var t=/(?:^|\s)nocode(?:\s|$)/,q=/\r\n?|\n/,l=a.ownerDocument,n=l.createElement("li");a.firstChild;)n.appendChild(a.firstChild); +for(var b=[n],p=0;p=+m[1],d=/\n/g,t=a.a,q=t.length,f=0,l=a.c,n=l.length,c=0,b=a.g,p=b.length,w=0;b[p]=q;var r,e;for(e=r=0;e=h&&(c+=2);f>=k&&(w+=2)}}finally{g&&(g.style.display=a)}}catch(y){D.console&&console.log(y&&y.stack||y)}}var D="undefined"!==typeof window? +window:{},B=["break,continue,do,else,for,if,return,while"],F=[[B,"auto,case,char,const,default,double,enum,extern,float,goto,inline,int,long,register,restrict,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],H=[F,"alignas,alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,delegate,dynamic_cast,explicit,export,friend,generic,late_check,mutable,namespace,noexcept,noreturn,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"], +O=[F,"abstract,assert,boolean,byte,extends,finally,final,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient"],P=[F,"abstract,add,alias,as,ascending,async,await,base,bool,by,byte,checked,decimal,delegate,descending,dynamic,event,finally,fixed,foreach,from,get,global,group,implicit,in,interface,internal,into,is,join,let,lock,null,object,out,override,orderby,params,partial,readonly,ref,remove,sbyte,sealed,select,set,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,value,var,virtual,where,yield"], +F=[F,"abstract,async,await,constructor,debugger,enum,eval,export,from,function,get,import,implements,instanceof,interface,let,null,of,set,undefined,var,with,yield,Infinity,NaN"],Q=[B,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],R=[B,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"], +B=[B,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],S=/^(DIR|FILE|array|vector|(de|priority_)?queue|(forward_)?list|stack|(const_)?(reverse_)?iterator|(unordered_)?(multi)?(set|map)|bitset|u?(int|float)\d*)\b/,W=/\S/,X=x({keywords:[H,P,O,F,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",Q,R,B],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}), +I={};t(X,["default-code"]);t(G([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),"default-markup htm html mxml xhtml xml xsl".split(" "));t(G([["pln",/^[\s]+/, +null," \t\r\n"],["atv",/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],["pun",/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]); +t(G([],[["atv",/^[\s\S]+/]]),["uq.val"]);t(x({keywords:H,hashComments:!0,cStyleComments:!0,types:S}),"c cc cpp cxx cyc m".split(" "));t(x({keywords:"null,true,false"}),["json"]);t(x({keywords:P,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:S}),["cs"]);t(x({keywords:O,cStyleComments:!0}),["java"]);t(x({keywords:B,hashComments:!0,multiLineStrings:!0}),["bash","bsh","csh","sh"]);t(x({keywords:Q,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),["cv","py","python"]);t(x({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END", +hashComments:!0,multiLineStrings:!0,regexLiterals:2}),["perl","pl","pm"]);t(x({keywords:R,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb","ruby"]);t(x({keywords:F,cStyleComments:!0,regexLiterals:!0}),["javascript","js","ts","typescript"]);t(x({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,throw,true,try,unless,until,when,while,yes",hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0, +regexLiterals:!0}),["coffee"]);t(G([],[["str",/^[\s\S]+/]]),["regex"]);var Y=D.PR={createSimpleLexer:G,registerLangHandler:t,sourceDecorator:x,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ",prettyPrintOne:D.prettyPrintOne=function(a,d,f){f=f||!1;d=d||null;var c=document.createElement("div");c.innerHTML="
    "+a+"
    "; +c=c.firstChild;f&&L(c,f,!0);M({j:d,m:f,h:c,l:1,a:null,i:null,c:null,g:null});return c.innerHTML},prettyPrint:D.prettyPrint=function(a,d){function f(){for(var c=D.PR_SHOULD_USE_CONTINUATION?b.now()+250:Infinity;p=c?parseInt(e.substring(1),8):"u"===c||"x"===c?parseInt(e.substring(2),16):e.charCodeAt(1)}function f(e){if(32>e)return(16>e?"\\x0":"\\x")+e.toString(16);e=String.fromCharCode(e); +return"\\"===e||"-"===e||"]"===e||"^"===e?"\\"+e:e}function c(e){var c=e.substring(1,e.length-1).match(RegExp("\\\\u[0-9A-Fa-f]{4}|\\\\x[0-9A-Fa-f]{2}|\\\\[0-3][0-7]{0,2}|\\\\[0-7]{1,2}|\\\\[\\s\\S]|-|[^-\\\\]","g"));e=[];var a="^"===c[0],b=["["];a&&b.push("^");for(var a=a?1:0,h=c.length;ap||122p||90p||122m[0]&&(m[1]+1>m[0]&&b.push("-"),b.push(f(m[1])));b.push("]");return b.join("")}function g(e){for(var a=e.source.match(RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)", +"g")),b=a.length,d=[],h=0,m=0;h/,null])):d.push(["com",/^#[^\r\n]*/,null,"#"]));a.cStyleComments&&(f.push(["com",/^\/\/[^\r\n]*/,null]),f.push(["com",/^\/\*[\s\S]*?(?:\*\/|$)/, +null]));if(c=a.regexLiterals){var g=(c=1|\\/=?|::?|<>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*("+("/(?=[^/*"+c+"])(?:[^/\\x5B\\x5C"+c+"]|\\x5C"+g+"|\\x5B(?:[^\\x5C\\x5D"+c+"]|\\x5C"+g+")*(?:\\x5D|$))+/")+")")])}(c=a.types)&&f.push(["typ",c]);c=(""+a.keywords).replace(/^ | $/g,"");c.length&&f.push(["kwd", +new RegExp("^(?:"+c.replace(/[\s,]+/g,"|")+")\\b"),null]);d.push(["pln",/^\s+/,null," \r\n\t\u00a0"]);c="^.[^\\s\\w.$@'\"`/\\\\]*";a.regexLiterals&&(c+="(?!s*/)");f.push(["lit",/^@[a-z_$][a-z_$@0-9]*/i,null],["typ",/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],["pln",/^[a-z_$][a-z_$@0-9]*/i,null],["lit",/^(?:0x[a-f0-9]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+\-]?\d+)?)[a-z]*/i,null,"0123456789"],["pln",/^\\[\s\S]?/,null],["pun",new RegExp(c),null]);return E(d,f)}function B(a,d,f){function c(a){var b= +a.nodeType;if(1==b&&!r.test(a.className))if("br"===a.nodeName.toLowerCase())g(a),a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)c(a);else if((3==b||4==b)&&f){var e=a.nodeValue,d=e.match(n);d&&(b=e.substring(0,d.index),a.nodeValue=b,(e=e.substring(d.index+d[0].length))&&a.parentNode.insertBefore(q.createTextNode(e),a.nextSibling),g(a),b||a.parentNode.removeChild(a))}}function g(a){function c(a,b){var e=b?a.cloneNode(!1):a,p=a.parentNode;if(p){var p=c(p,1),d=a.nextSibling; +p.appendChild(e);for(var f=d;f;f=d)d=f.nextSibling,p.appendChild(f)}return e}for(;!a.nextSibling;)if(a=a.parentNode,!a)return;a=c(a.nextSibling,0);for(var e;(e=a.parentNode)&&1===e.nodeType;)a=e;b.push(a)}for(var r=/(?:^|\s)nocode(?:\s|$)/,n=/\r\n?|\n/,q=a.ownerDocument,k=q.createElement("li");a.firstChild;)k.appendChild(a.firstChild);for(var b=[k],t=0;t=+g[1],d=/\n/g,r=a.a,k=r.length,f=0,q=a.c,n=q.length,c=0,b=a.g,t=b.length,v=0;b[t]=k;var u,e;for(e=u=0;e=m&&(c+=2);f>=p&&(v+=2)}}finally{h&&(h.style.display=a)}}catch(y){Q.console&&console.log(y&&y.stack||y)}}var Q="undefined"!==typeof window?window:{},J=["break,continue,do,else,for,if,return,while"],K=[[J,"auto,case,char,const,default,double,enum,extern,float,goto,inline,int,long,register,restrict,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], +"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],R=[K,"alignas,alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,delegate,dynamic_cast,explicit,export,friend,generic,late_check,mutable,namespace,noexcept,noreturn,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],L=[K,"abstract,assert,boolean,byte,extends,finally,final,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient"], +M=[K,"abstract,add,alias,as,ascending,async,await,base,bool,by,byte,checked,decimal,delegate,descending,dynamic,event,finally,fixed,foreach,from,get,global,group,implicit,in,interface,internal,into,is,join,let,lock,null,object,out,override,orderby,params,partial,readonly,ref,remove,sbyte,sealed,select,set,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,value,var,virtual,where,yield"],K=[K,"abstract,async,await,constructor,debugger,enum,eval,export,from,function,get,import,implements,instanceof,interface,let,null,of,set,undefined,var,with,yield,Infinity,NaN"], +N=[J,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],O=[J,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],J=[J,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],P=/^(DIR|FILE|array|vector|(de|priority_)?queue|(forward_)?list|stack|(const_)?(reverse_)?iterator|(unordered_)?(multi)?(set|map)|bitset|u?(int|float)\d*)\b/, +S=/\S/,T=v({keywords:[R,M,L,K,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",N,O,J],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),V={};n(T,["default-code"]);n(E([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-", +/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),"default-markup htm html mxml xhtml xml xsl".split(" "));n(E([["pln",/^[\s]+/,null," \t\r\n"],["atv",/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/], +["pun",/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);n(E([],[["atv",/^[\s\S]+/]]),["uq.val"]);n(v({keywords:R,hashComments:!0,cStyleComments:!0,types:P}),"c cc cpp cxx cyc m".split(" "));n(v({keywords:"null,true,false"}),["json"]);n(v({keywords:M,hashComments:!0,cStyleComments:!0, +verbatimStrings:!0,types:P}),["cs"]);n(v({keywords:L,cStyleComments:!0}),["java"]);n(v({keywords:J,hashComments:!0,multiLineStrings:!0}),["bash","bsh","csh","sh"]);n(v({keywords:N,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),["cv","py","python"]);n(v({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:2}), +["perl","pl","pm"]);n(v({keywords:O,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb","ruby"]);n(v({keywords:K,cStyleComments:!0,regexLiterals:!0}),["javascript","js","ts","typescript"]);n(v({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,throw,true,try,unless,until,when,while,yes",hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);n(E([],[["str",/^[\s\S]+/]]), +["regex"]);var U=Q.PR={createSimpleLexer:E,registerLangHandler:n,sourceDecorator:v,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ",prettyPrintOne:function(a,d,f){f=f||!1;d=d||null;var c=document.createElement("div");c.innerHTML="
    "+a+"
    ";c=c.firstChild;f&&B(c,f,!0);H({j:d,m:f,h:c,l:1,a:null,i:null,c:null,g:null}); +return c.innerHTML},prettyPrint:g=function(a,d){function f(){for(var c=Q.PR_SHOULD_USE_CONTINUATION?b.now()+250:Infinity;t