├── .babelrc
├── .editorconfig
├── .gitignore
├── .jshintrc
├── LICENSE
├── README.md
├── __tests__
├── import-test.js
├── mouseBeyond-test.js
├── populateTreeIds-test.js
└── swapElements-test.js
├── bundle.js
├── css
└── sortable.css
├── examples
├── basic-grid
│ ├── SortableGrid.js
│ ├── SortableItem.js
│ └── index.js
├── basic-list
│ ├── SortableItem.js
│ ├── SortableList.js
│ └── index.js
├── html-table
│ ├── SortableItem.js
│ ├── SortableList.js
│ └── index.js
├── index.html
├── main.js
└── redux
│ ├── SortableItem.js
│ ├── SortableList.js
│ └── index.js
├── index.html
├── lib
├── SortableComposition.js
├── helpers.js
├── index.js
└── standalone
│ ├── react-sortable.js
│ └── react-sortable.min.js
├── package.json
├── src
├── SortableComposition.js
├── helpers.js
└── index.js
├── webdriver
├── spec
│ └── drag&drop.js
└── wdio-local.conf.js
├── webpack.config.js
├── webpack.devConfig.js
└── webpack.standalone.js
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | "es2015",
4 | "react",
5 | "stage-0"
6 | ]
7 | }
8 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # editorconfig.org
2 | root = true
3 |
4 | [*]
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | charset = utf-8
9 | trim_trailing_whitespace = true
10 | insert_final_newline = true
11 |
12 | [*.md]
13 | trim_trailing_whitespace = false
14 |
15 |
16 | [**.jsx]
17 | e4x = true
18 | indent_style = space
19 | indent_size = 2
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | bower_components
2 | node_modules
3 | .idea
4 | bundle.js.map
5 | npm-debug.log
6 |
--------------------------------------------------------------------------------
/.jshintrc:
--------------------------------------------------------------------------------
1 | {
2 | "esversion": 6
3 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 Daniel Stocks
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React Sortable
2 |
3 |
4 | [](https://david-dm.org/danielstocks/react-sortable)
5 | [](https://www.npmjs.com/package/react-sortable)
6 | [](https://www.npmjs.com/package/react-sortable)
7 |
8 |
9 | Higher-order component for creating sortable lists with minimalistic implementation and without polyfills.
10 | Using just React.js and HTML5 [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent) interface.
11 |
12 | Mainly tested in latest stable Webkit, Firefox and IE.
13 |
14 | Check out [demo](http://webcloud.se/react-sortable) and [source](https://github.com/danielstocks/react-sortable/blob/master/src/SortableComposition.js).
15 |
16 |
17 | ## Installation
18 |
19 | To install a stable release use:
20 |
21 | `npm i react-sortable --save`
22 |
23 | ## Example
24 |
25 | First import the necessary dependencies.
26 |
27 | ```js
28 | import React from 'react';
29 | import ReactDOM from 'react-dom';
30 | import { sortable } from 'react-sortable';
31 |
32 | ```
33 |
34 | Then create a component for the single item of the list.
35 |
36 | ```js
37 | class Item extends React.Component {
38 | render() {
39 | return (
40 |
41 | {this.props.children}
42 |
43 | )
44 | }
45 | }
46 |
47 |
48 | var SortableItem = sortable(Item);
49 |
50 | ```
51 |
52 | And create component for the whole list, which will be the main component.
53 |
54 | ```js
55 | class SortableList extends React.Component {
56 |
57 | state = {
58 | items: this.props.items
59 | };
60 |
61 | onSortItems = (items) => {
62 | this.setState({
63 | items: items
64 | });
65 | }
66 |
67 | render() {
68 | const { items } = this.state;
69 | var listItems = items.map((item, i) => {
70 | return (
71 | {item}
76 | );
77 | });
78 |
79 | return (
80 |
83 | )
84 | }
85 | };
86 |
87 | ```
88 |
89 | Now you can pass a list of items to the main component and render the whole result.
90 |
91 | ```js
92 |
93 |
94 | var items = [
95 | "Gold",
96 | "Crimson",
97 | "Hotpink",
98 | "Blueviolet",
99 | "Cornflowerblue",
100 | "Skyblue",
101 | "Lightblue",
102 | "Aquamarine",
103 | "Burlywood"
104 | ]
105 |
106 | ReactDOM.render(
107 | ,
108 | document.body
109 | );
110 |
111 | ```
112 |
113 | You can see this simple working demo in the `./example` folder.
114 | For visual styling, you can add className of your choice.
115 |
116 | ### How it works
117 |
118 | Component will automatically attach the necessary drag event handlers.
119 |
120 | It expects the following properties to be defined:
121 |
122 | - **key** (position of item in virtaul dom [recommendation](http://facebook.github.io/react/docs/reconciliation.html#keys))
123 | - **onSortItems** (function called when an item is moved - dispatching if Redux action)
124 | - **items** (array of items to be sorted)
125 | - **sortId** (index of item in array)
126 |
127 |
128 | ## Differences from [react-dnd](http://gaearon.github.io/react-dnd/examples-sortable-simple.html)
129 | - fewer lines of code, easier to understand and modify
130 | - can handle both horizontal and vertical dragging
131 | - code is documented and covered with unit tests
132 |
133 | ## Touch support
134 |
135 | Unfortunately, at the moment there is no [support](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent#Browser_compatibility) of this interface in mobile browsers.
136 |
137 | ## Purpose of this repo
138 |
139 | This repository was published back in 2014 and was pretty much the very first implementation of drag and drop sortable list for React.js. Nowadays since there are other repositories which are well maintained ([react-beautiful-dnd](https://github.com/atlassian/react-beautiful-dnd), [react-sortable-hoc](https://github.com/clauderic/react-sortable-hoc)), I can recommend to use some of them in your project. This repository is now rather a showcase of what can be done just with simple React.js component and bare HTML5 API, having as few lines of code as possible. It can serve as inspiration for somebody who would like to reimplement this functionality from scratch.
140 |
141 | ## Mainteners
142 |
143 | * [github.com/danielstocks](https://github.com/danielstocks)
144 | * [github.com/Dharmoslap](https://github.com/Dharmoslap)
145 |
--------------------------------------------------------------------------------
/__tests__/import-test.js:
--------------------------------------------------------------------------------
1 | jest.autoMockOff();
2 |
3 | describe('import test', () => {
4 |
5 | it('should import sortable', () => {
6 |
7 | // when
8 | var sortable = require('../src').sortable;
9 |
10 | // then
11 | expect(sortable).not.toBeUndefined();
12 | });
13 |
14 |
15 | // Sortable with uppercase S for compatibility reasons
16 | // danielstocks/react-sortable/issues/57
17 | // TODO: remove with release 2.0.0
18 | it('should import Sortable (uppercase S)', () => {
19 |
20 | // when
21 | var SortableUppercase = require('../src').Sortable;
22 |
23 | // then
24 | expect(SortableUppercase).not.toBeUndefined();
25 | });
26 |
27 | });
28 |
--------------------------------------------------------------------------------
/__tests__/mouseBeyond-test.js:
--------------------------------------------------------------------------------
1 | jest.autoMockOff();
2 |
3 | describe('checks if mouse pointer has reached over the breakpoint in next element', () => {
4 |
5 | const elementPos = 100;
6 | const elementSize = 400;
7 |
8 | it('gives false if mouse is outside of next element', () => {
9 | const {isMouseBeyond} = require('../src/SortableComposition');
10 | const mousePos = 0;
11 | expect(isMouseBeyond(mousePos, elementPos, elementSize)).toBe(false);
12 | });
13 |
14 | it('gives false if mouse is inside of next element, but still hasn\'t reached the breakpoint', () => {
15 | const {isMouseBeyond} = require('../src/SortableComposition');
16 | const mousePos = 300;
17 | expect(isMouseBeyond(mousePos, elementPos, elementSize)).toBe(false);
18 | });
19 |
20 | it('gives true if mouse is inside of next element and has just reached the breakpoint', () => {
21 | const {isMouseBeyond} = require('../src/SortableComposition');
22 | const mousePos = 301;
23 | expect(isMouseBeyond(mousePos, elementPos, elementSize)).toBe(true);
24 | });
25 |
26 | it('gives true if mouse is on the edge of next element, already over the breakpoint', () => {
27 | const {isMouseBeyond} = require('../src/SortableComposition');
28 | const mousePos = 500;
29 | expect(isMouseBeyond(mousePos, elementPos, elementSize)).toBe(true);
30 | });
31 |
32 |
33 | });
34 |
35 |
36 | /*describe('checks if mouse pointer has reached over the breakpoint in previous element', () => {
37 |
38 | const elementPos = 100;
39 | const elementSize = 400;
40 |
41 | it('gives false if mouse is outside of previous element', () => {
42 | const {isMouseBeyond} = require('../src/SortableComposition');
43 | const mousePos = 500;
44 | expect(isMouseBeyond(mousePos, elementPos, elementSize)).toBe(false);
45 | });
46 |
47 | it('gives false if mouse is inside of previous element, but still hasn\'t reached the breakpoint', () => {
48 | const {isMouseBeyond} = require('../src/SortableComposition');
49 | const mousePos = 301;
50 | expect(isMouseBeyond(mousePos, elementPos, elementSize)).toBe(false);
51 | });
52 |
53 | it('gives true if mouse is inside of previous element and has just reached the breakpoint', () => {
54 | const {isMouseBeyond} = require('../src/SortableComposition');
55 | const mousePos = 300;
56 | expect(isMouseBeyond(mousePos, elementPos, elementSize)).toBe(true);
57 | });
58 |
59 | it('gives true if mouse is on the edge of previous element, already over the breakpoint', () => {
60 | const {isMouseBeyond} = require('../src/SortableComposition');
61 | const mousePos = 0;
62 | expect(isMouseBeyond(mousePos, elementPos, elementSize)).toBe(true);
63 | });
64 |
65 |
66 | });*/
67 |
--------------------------------------------------------------------------------
/__tests__/populateTreeIds-test.js:
--------------------------------------------------------------------------------
1 | jest.autoMockOff();
2 |
3 | xdescribe('swap elements in array', () => {
4 |
5 | it('swaps two elements based on indexFrom and indexTo', () => {
6 | var fixture = {
7 | module: "root",
8 | children: [
9 | {
10 | "module":"section",
11 | "children":
12 | [
13 | {
14 | "module":"header",
15 | },
16 | {
17 | "module":"paragraph",
18 | },
19 | {
20 | "module":"image",
21 | },
22 | {
23 | "module":"section",
24 | "children":
25 | [
26 | {
27 | "module":"header",
28 | },
29 | {
30 | "module":"paragraph",
31 | },
32 | {
33 | "module":"image",
34 | }
35 | ]
36 | },
37 | ]
38 | },
39 | {
40 | "module":"section",
41 | "children":[
42 | {
43 | "module":"column",
44 | },
45 | {
46 | "module":"video",
47 | }
48 | ]
49 | },
50 | {
51 | "module":"image"
52 | },
53 | ]
54 | }
55 |
56 | var result ={
57 | "module":"root",
58 | "children":[
59 | {
60 | "module":"section",
61 | "children":[
62 | {
63 | "module":"header",
64 | "id":2,
65 | "parent_id":1,
66 | "children":[
67 |
68 | ]
69 | },
70 | {
71 | "module":"paragraph",
72 | "id":3,
73 | "parent_id":1,
74 | "children":[
75 |
76 | ]
77 | },
78 | {
79 | "module":"image",
80 | "id":4,
81 | "parent_id":1,
82 | "children":[
83 |
84 | ]
85 | },
86 | {
87 | "module":"section",
88 | "children":[
89 | {
90 | "module":"header",
91 | "id":6,
92 | "parent_id":5,
93 | "children":[
94 |
95 | ]
96 | },
97 | {
98 | "module":"paragraph",
99 | "id":7,
100 | "parent_id":5,
101 | "children":[
102 |
103 | ]
104 | },
105 | {
106 | "module":"image",
107 | "id":8,
108 | "parent_id":5,
109 | "children":[
110 |
111 | ]
112 | }
113 | ],
114 | "id":5,
115 | "parent_id":1
116 | }
117 | ],
118 | "id":1,
119 | "parent_id":0
120 | },
121 | {
122 | "module":"section",
123 | "children":[
124 | {
125 | "module":"column",
126 | "id":10,
127 | "parent_id":9,
128 | "children":[
129 |
130 | ]
131 | },
132 | {
133 | "module":"video",
134 | "id":11,
135 | "parent_id":9,
136 | "children":[
137 |
138 | ]
139 | }
140 | ],
141 | "id":9,
142 | "parent_id":0
143 | },
144 | {
145 | "module":"image",
146 | "id":12,
147 | "parent_id":0,
148 | "children":[
149 |
150 | ]
151 | }
152 | ]
153 | }
154 |
155 | const {populateTreeIds} = require('../src/SortableNestedComposition');
156 | expect(populateTreeIds(fixture)).toEqual(result);
157 | });
158 |
159 |
160 |
161 | });
162 |
163 |
--------------------------------------------------------------------------------
/__tests__/swapElements-test.js:
--------------------------------------------------------------------------------
1 | jest.autoMockOff();
2 |
3 | describe('swap elements in array', () => {
4 |
5 | it('swaps two elements based on indexFrom and indexTo', () => {
6 | var items = ["Gold", "Crimson", "Hotpink", "Blueviolet", "Cornflowerblue"];
7 | const {swapArrayElements} = require('../src/SortableComposition');
8 | expect(swapArrayElements(items, 1, 2)).toEqual(["Gold", "Hotpink", "Crimson", "Blueviolet", "Cornflowerblue"]);
9 | });
10 |
11 | it('leaves array the same if indexFrom and indexTo are the same', () => {
12 | var items = ["Gold", "Crimson", "Hotpink", "Blueviolet", "Cornflowerblue"];
13 | const {swapArrayElements} = require('../src/SortableComposition');
14 | expect(swapArrayElements(items, 0, 0)).toEqual(["Gold", "Crimson", "Hotpink", "Blueviolet", "Cornflowerblue"]);
15 | });
16 |
17 | });
18 |
19 |
--------------------------------------------------------------------------------
/css/sortable.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 40px;
3 | width: 620px;
4 | font-family: arial;
5 | font-size: 15px;
6 | }
7 |
8 |
9 | /* list demo */
10 |
11 | .sortable-list {
12 | list-style: none;
13 | margin:0;
14 | padding:0;
15 | float:left;
16 | width:200px;
17 | background:#ddd;
18 | }
19 |
20 | .sortable-list li {
21 | padding: 10px;
22 | color: #666;
23 | line-height: 17px;
24 | position: relative;
25 | -webkit-user-drag: element;
26 | }
27 |
28 |
29 |
30 |
31 | /* grid demo */
32 |
33 | .sortable-grid {
34 | padding-left: 0;
35 | }
36 |
37 | .sortable-grid li {
38 | height: 111px;
39 | width: 130px;
40 | float: left;
41 | color: #fff;
42 | position: relative;
43 | list-style: none;
44 | -webkit-user-drag: element;
45 | }
46 |
47 | .sortable-grid li span {
48 | font-size: 10px;
49 | position: absolute;
50 | -webkit-transform: translate(-50%, -50%);
51 | -moz-transform: translate(-50%, -50%);
52 | transform: translate(-50%, -50%);
53 | left: 50%;
54 | top: 50%;
55 | text-shadow: 0px 0px 2px rgba(0,0,0,0.5);
56 | }
57 |
--------------------------------------------------------------------------------
/examples/basic-grid/SortableGrid.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 | import SortableItem from './SortableItem'
4 |
5 | export default class SortableGrid extends React.Component {
6 |
7 | state = {
8 | items: this.props.items
9 | }
10 |
11 | onSortItems = (items) => {
12 | this.setState({
13 | items: items
14 | })
15 | }
16 |
17 | render() {
18 | const { items } = this.state
19 |
20 | var gridItems = items.map((item, i) => {
21 | return (
22 |
27 | {item}
28 |
29 | );
30 | });
31 |
32 | return (
33 |
36 | )
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/examples/basic-grid/SortableItem.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { sortable, HORIZONTAL } from '../../src'
3 |
4 | class Item extends React.Component {
5 | render() {
6 | return (
7 |
8 | {this.props.children}
9 |
10 | )
11 | }
12 | }
13 |
14 | export default sortable(Item, HORIZONTAL)
15 |
--------------------------------------------------------------------------------
/examples/basic-grid/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 |
4 | import SortableList from './SortableList'
5 |
6 | var items = [
7 | "Gold",
8 | "Crimson",
9 | "Hotpink",
10 | "Blueviolet",
11 | "Cornflowerblue",
12 | "Skyblue",
13 | "Lightblue",
14 | "Aquamarine",
15 | "Burlywood"
16 | ]
17 |
18 | ReactDOM.render(
19 | ,
20 | document.getElementById('app')
21 | )
22 |
--------------------------------------------------------------------------------
/examples/basic-list/SortableItem.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { sortable } from '../../src'
3 |
4 | class Item extends React.Component {
5 | render() {
6 | return (
7 |
8 | {this.props.children}
9 |
10 | )
11 | }
12 | }
13 |
14 | export default sortable(Item)
15 |
--------------------------------------------------------------------------------
/examples/basic-list/SortableList.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import SortableItem from './SortableItem'
3 |
4 | export default class SortableList extends React.Component {
5 |
6 | state = {
7 | items: this.props.items
8 | };
9 |
10 | onSortItems = (items) => {
11 | this.setState({
12 | items: items
13 | });
14 | }
15 |
16 | render() {
17 | const { items } = this.state;
18 | var listItems = items.map((item, i) => {
19 | return (
20 |
25 | {item}
26 |
27 | )
28 | })
29 |
30 | return (
31 |
34 | )
35 | }
36 | }
37 |
38 |
--------------------------------------------------------------------------------
/examples/basic-list/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 |
4 | import SortableList from './SortableList'
5 |
6 | var items = [
7 | "Gold",
8 | "Crimson",
9 | "Hotpink",
10 | "Blueviolet",
11 | "Cornflowerblue",
12 | "Skyblue",
13 | "Lightblue",
14 | "Aquamarine",
15 | "Burlywood"
16 | ]
17 |
18 | ReactDOM.render(
19 | ,
20 | document.getElementById('app')
21 | )
22 |
--------------------------------------------------------------------------------
/examples/html-table/SortableItem.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { sortable } from '../../src'
3 |
4 | class Item extends React.Component {
5 | render() {
6 | return (
7 |
8 | {this.props.children} |
9 | I'm empty |
10 |
11 | )
12 | }
13 | }
14 |
15 | export default sortable(Item)
16 |
--------------------------------------------------------------------------------
/examples/html-table/SortableList.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import SortableListItem from './SortableItem'
3 |
4 | export default class SortableList extends React.Component {
5 |
6 | state = {
7 | items: this.props.items
8 | };
9 |
10 | onSortItems = (items) => {
11 | this.setState({
12 | items: items
13 | });
14 | }
15 |
16 | render() {
17 | const { items } = this.state;
18 | var listItems = items.map((item, i) => {
19 | return (
20 | {item}
25 | );
26 | });
27 |
28 | return (
29 |
32 | )
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/examples/html-table/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 |
4 | import SortableList from './SortableList'
5 |
6 | var items = [
7 | "Gold",
8 | "Crimson",
9 | "Hotpink",
10 | "Blueviolet",
11 | "Cornflowerblue",
12 | "Skyblue",
13 | "Lightblue",
14 | "Aquamarine",
15 | "Burlywood"
16 | ]
17 |
18 | ReactDOM.render(
19 | ,
20 | document.getElementById('app')
21 | )
22 |
--------------------------------------------------------------------------------
/examples/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | React Sortable
7 |
8 |
9 |
10 |
11 |
12 | React Sortable
13 | View source and documentation on
14 | Github.
15 |
16 |
You can also try dragging items between the grid and the list
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/main.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 |
4 | import SortableList from './basic-list/SortableList'
5 | import SortableGrid from './basic-grid/SortableGrid'
6 |
7 | var items = [
8 | "Gold",
9 | "Crimson",
10 | "Hotpink",
11 | "Blueviolet",
12 | "Cornflowerblue",
13 | "Skyblue",
14 | "Lightblue",
15 | "Aquamarine",
16 | "Burlywood"
17 | ]
18 |
19 | ReactDOM.render(
20 |
21 |
22 |
23 |
,
24 | document.getElementById('app')
25 | )
26 |
--------------------------------------------------------------------------------
/examples/redux/SortableItem.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { sortable } from '../../src'
3 |
4 | class Item extends React.Component {
5 | render() {
6 | return (
7 |
8 | {this.props.children}
9 |
10 | )
11 | }
12 | }
13 |
14 | export default sortable(Item)
15 |
--------------------------------------------------------------------------------
/examples/redux/SortableList.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import SortableItem from './SortableItem'
3 |
4 | export default class SortableList extends React.Component {
5 |
6 | render() {
7 | const { items, onSortItems } = this.props;
8 | var listItems = items.map((item, i) => {
9 | return (
10 |
15 | {item}
16 |
17 | );
18 | });
19 |
20 | return (
21 |
22 | )
23 | }
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/examples/redux/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 | import { Provider } from 'react-redux'
4 | import { createStore } from 'redux'
5 |
6 | import SortableList from './SortableList';
7 |
8 | let initialState = {
9 | items: [
10 | "Gold",
11 | "Crimson",
12 | "Hotpink",
13 | "Blueviolet",
14 | "Cornflowerblue",
15 | "Skyblue",
16 | "Lightblue",
17 | "Aquamarine",
18 | "Burlywood"
19 | ]
20 | }
21 |
22 | const sortableStore = (state = initialState, action) => {
23 | switch (action.type) {
24 | case 'SORT_ITEMS':
25 | return Object.assign({}, state, {
26 | items: action.items
27 | })
28 | default:
29 | return state
30 | }
31 | }
32 |
33 |
34 | let store = createStore(sortableStore, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
35 |
36 | export const sortItems = items => {
37 | return {
38 | type: 'SORT_ITEMS',
39 | items
40 | }
41 | }
42 |
43 | const render = () => {
44 | ReactDOM.render(
45 |
46 | {
49 | store.dispatch(sortItems(items))
50 | }} />
51 | ,
52 | document.getElementById('app')
53 | )
54 | }
55 |
56 | store.subscribe(render)
57 | render()
58 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | React Sortable
7 |
8 |
9 |
10 |
11 |
12 | webcloud / React Sortable
13 | React Sortable
14 | View source and documentation on
15 | Github.
16 |
17 |
You can also try dragging items between the grid and the list
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/lib/SortableComposition.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.HORIZONTAL = exports.VERTICAL = undefined;
7 |
8 | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
9 |
10 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
11 |
12 | exports.SortableComposition = SortableComposition;
13 |
14 | var _react = require('react');
15 |
16 | var _react2 = _interopRequireDefault(_react);
17 |
18 | var _propTypes = require('prop-types');
19 |
20 | var _propTypes2 = _interopRequireDefault(_propTypes);
21 |
22 | var _helpers = require('./helpers.js');
23 |
24 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25 |
26 | function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
27 |
28 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
29 |
30 | function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
31 |
32 | function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
33 |
34 | var VERTICAL = exports.VERTICAL = 'VERTICAL';
35 | var HORIZONTAL = exports.HORIZONTAL = 'HORIZONTAL';
36 |
37 | /*** Higher-order component - this component works like a factory for draggable items */
38 |
39 | var draggingIndex = null;
40 |
41 | function SortableComposition(Component) {
42 | var flowDirection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : VERTICAL;
43 |
44 |
45 | return function (_React$Component) {
46 | _inherits(Sortable, _React$Component);
47 |
48 | function Sortable() {
49 | var _ref;
50 |
51 | var _temp, _this, _ret;
52 |
53 | _classCallCheck(this, Sortable);
54 |
55 | for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
56 | args[_key] = arguments[_key];
57 | }
58 |
59 | return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Sortable.__proto__ || Object.getPrototypeOf(Sortable)).call.apply(_ref, [this].concat(args))), _this), _this.sortEnd = function (e) {
60 | e.preventDefault();
61 | draggingIndex = null;
62 | }, _this.sortStart = function (e) {
63 | draggingIndex = e.currentTarget.dataset.id;
64 | var dt = e.dataTransfer;
65 | if (dt !== undefined) {
66 | e.dataTransfer.setData('text', e.target.innerHTML);
67 |
68 | //fix http://stackoverflow.com/questions/27656183/preserve-appearance-of-dragged-a-element-when-using-html5-draggable-attribute
69 | if (dt.setDragImage && e.currentTarget.tagName.toLowerCase() === 'a') {
70 | dt.setDragImage(e.target, 0, 0);
71 | }
72 | }
73 | }, _this.dragOver = function (e) {
74 | e.preventDefault();
75 | var _this$props = _this.props,
76 | moveInMiddle = _this$props.moveInMiddle,
77 | sortId = _this$props.sortId;
78 |
79 | var overEl = e.currentTarget; //underlying element
80 | var indexDragged = Number(overEl.dataset.id); //index of underlying element in the set DOM elements
81 | var indexFrom = Number(draggingIndex);
82 | var height = overEl.getBoundingClientRect().height;
83 | var width = overEl.getBoundingClientRect().width;
84 | var positionX = e.clientX;
85 | var positionY = e.clientY;
86 | var topOffset = overEl.getBoundingClientRect().top;
87 | var leftOffset = overEl.getBoundingClientRect().left;
88 | var mouseBeyond = void 0;
89 | var items = _this.props.items;
90 |
91 |
92 | if (flowDirection === VERTICAL) {
93 | mouseBeyond = (0, _helpers.isMouseBeyond)(positionY, topOffset, height, moveInMiddle);
94 | }
95 |
96 | if (flowDirection === HORIZONTAL) {
97 | mouseBeyond = (0, _helpers.isMouseBeyond)(positionX, leftOffset, width, moveInMiddle);
98 | }
99 |
100 | var shouldSwapItems = _helpers.isMouseBeyond && indexDragged !== indexFrom;
101 |
102 | if (indexDragged !== indexFrom && mouseBeyond) {
103 | items = (0, _helpers.swapArrayElements)(items, indexFrom, indexDragged);
104 | draggingIndex = indexDragged;
105 | _this.props.onSortItems(items);
106 | }
107 | }, _temp), _possibleConstructorReturn(_this, _ret);
108 | }
109 |
110 | _createClass(Sortable, [{
111 | key: 'render',
112 | value: function render() {
113 | var newProps = Object.assign({}, this.props);
114 | delete newProps.onSortItems;
115 |
116 | var sortId = newProps.sortId,
117 | props = _objectWithoutProperties(newProps, ['sortId']);
118 |
119 | return _react2.default.createElement(Component, _extends({
120 | draggable: true,
121 | onDragOver: this.dragOver,
122 | onDragStart: this.sortStart,
123 | onDragEnd: this.sortEnd,
124 | onTouchStart: this.sortStart,
125 | onTouchMove: this.dragOver,
126 | onTouchEnd: this.sortEnd,
127 | 'data-id': sortId
128 | }, props));
129 | }
130 | }]);
131 |
132 | return Sortable;
133 | }(_react2.default.Component);
134 |
135 | Sortable.propTypes = {
136 | items: _propTypes2.default.array.isRequired,
137 | onSortItems: _propTypes2.default.func.isRequired,
138 | sortId: _propTypes2.default.number
139 | };
140 |
141 | Sortable.defaultProps = {
142 | moveInMiddle: false
143 | };
144 |
145 | return Sortable;
146 | }
--------------------------------------------------------------------------------
/lib/helpers.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.swapArrayElements = swapArrayElements;
7 | exports.isMouseBeyond = isMouseBeyond;
8 | /*** Helper functions - they are decoupled because of testability */
9 |
10 | /**
11 | * @param {array} items
12 | * @param {number} indexFrom
13 | * @param {number} indexTo
14 | * @returns {array}
15 | */
16 | function swapArrayElements(items, indexFrom, indexTo) {
17 | var item = items[indexTo];
18 | items[indexTo] = items[indexFrom];
19 | items[indexFrom] = item;
20 | return items;
21 | }
22 |
23 | /**
24 | * @param {number} mousePos
25 | * @param {number} elementPos
26 | * @param {number} elementSize
27 | * @returns {boolean}
28 | */
29 | function isMouseBeyond(mousePos, elementPos, elementSize, moveInMiddle) {
30 | var breakPoint;
31 | if (moveInMiddle) {
32 | breakPoint = elementSize / 2; //break point is set to the middle line of element
33 | } else {
34 | breakPoint = 0;
35 | }
36 | var mouseOverlap = mousePos - elementPos;
37 | return mouseOverlap > breakPoint;
38 | }
--------------------------------------------------------------------------------
/lib/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | var _SortableComposition = require('./SortableComposition');
8 |
9 | Object.defineProperty(exports, 'sortable', {
10 | enumerable: true,
11 | get: function get() {
12 | return _SortableComposition.SortableComposition;
13 | }
14 | });
15 | Object.defineProperty(exports, 'Sortable', {
16 | enumerable: true,
17 | get: function get() {
18 | return _SortableComposition.SortableComposition;
19 | }
20 | });
21 | Object.defineProperty(exports, 'HORIZONTAL', {
22 | enumerable: true,
23 | get: function get() {
24 | return _SortableComposition.HORIZONTAL;
25 | }
26 | });
27 | Object.defineProperty(exports, 'VERTICAL', {
28 | enumerable: true,
29 | get: function get() {
30 | return _SortableComposition.VERTICAL;
31 | }
32 | });
--------------------------------------------------------------------------------
/lib/standalone/react-sortable.js:
--------------------------------------------------------------------------------
1 | (function webpackUniversalModuleDefinition(root, factory) {
2 | if(typeof exports === 'object' && typeof module === 'object')
3 | module.exports = factory(require("React"));
4 | else if(typeof define === 'function' && define.amd)
5 | define(["React"], factory);
6 | else if(typeof exports === 'object')
7 | exports["Sortable"] = factory(require("React"));
8 | else
9 | root["Sortable"] = factory(root["React"]);
10 | })(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE_7__) {
11 | return /******/ (function(modules) { // webpackBootstrap
12 | /******/ // The module cache
13 | /******/ var installedModules = {};
14 | /******/
15 | /******/ // The require function
16 | /******/ function __webpack_require__(moduleId) {
17 | /******/
18 | /******/ // Check if module is in cache
19 | /******/ if(installedModules[moduleId]) {
20 | /******/ return installedModules[moduleId].exports;
21 | /******/ }
22 | /******/ // Create a new module (and put it into the cache)
23 | /******/ var module = installedModules[moduleId] = {
24 | /******/ i: moduleId,
25 | /******/ l: false,
26 | /******/ exports: {}
27 | /******/ };
28 | /******/
29 | /******/ // Execute the module function
30 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31 | /******/
32 | /******/ // Flag the module as loaded
33 | /******/ module.l = true;
34 | /******/
35 | /******/ // Return the exports of the module
36 | /******/ return module.exports;
37 | /******/ }
38 | /******/
39 | /******/
40 | /******/ // expose the modules object (__webpack_modules__)
41 | /******/ __webpack_require__.m = modules;
42 | /******/
43 | /******/ // expose the module cache
44 | /******/ __webpack_require__.c = installedModules;
45 | /******/
46 | /******/ // define getter function for harmony exports
47 | /******/ __webpack_require__.d = function(exports, name, getter) {
48 | /******/ if(!__webpack_require__.o(exports, name)) {
49 | /******/ Object.defineProperty(exports, name, {
50 | /******/ configurable: false,
51 | /******/ enumerable: true,
52 | /******/ get: getter
53 | /******/ });
54 | /******/ }
55 | /******/ };
56 | /******/
57 | /******/ // getDefaultExport function for compatibility with non-harmony modules
58 | /******/ __webpack_require__.n = function(module) {
59 | /******/ var getter = module && module.__esModule ?
60 | /******/ function getDefault() { return module['default']; } :
61 | /******/ function getModuleExports() { return module; };
62 | /******/ __webpack_require__.d(getter, 'a', getter);
63 | /******/ return getter;
64 | /******/ };
65 | /******/
66 | /******/ // Object.prototype.hasOwnProperty.call
67 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
68 | /******/
69 | /******/ // __webpack_public_path__
70 | /******/ __webpack_require__.p = "";
71 | /******/
72 | /******/ // Load entry module and return exports
73 | /******/ return __webpack_require__(__webpack_require__.s = 5);
74 | /******/ })
75 | /************************************************************************/
76 | /******/ ([
77 | /* 0 */
78 | /***/ (function(module, exports) {
79 |
80 | // shim for using process in browser
81 | var process = module.exports = {};
82 |
83 | // cached from whatever global is present so that test runners that stub it
84 | // don't break things. But we need to wrap it in a try catch in case it is
85 | // wrapped in strict mode code which doesn't define any globals. It's inside a
86 | // function because try/catches deoptimize in certain engines.
87 |
88 | var cachedSetTimeout;
89 | var cachedClearTimeout;
90 |
91 | function defaultSetTimout() {
92 | throw new Error('setTimeout has not been defined');
93 | }
94 | function defaultClearTimeout () {
95 | throw new Error('clearTimeout has not been defined');
96 | }
97 | (function () {
98 | try {
99 | if (typeof setTimeout === 'function') {
100 | cachedSetTimeout = setTimeout;
101 | } else {
102 | cachedSetTimeout = defaultSetTimout;
103 | }
104 | } catch (e) {
105 | cachedSetTimeout = defaultSetTimout;
106 | }
107 | try {
108 | if (typeof clearTimeout === 'function') {
109 | cachedClearTimeout = clearTimeout;
110 | } else {
111 | cachedClearTimeout = defaultClearTimeout;
112 | }
113 | } catch (e) {
114 | cachedClearTimeout = defaultClearTimeout;
115 | }
116 | } ())
117 | function runTimeout(fun) {
118 | if (cachedSetTimeout === setTimeout) {
119 | //normal enviroments in sane situations
120 | return setTimeout(fun, 0);
121 | }
122 | // if setTimeout wasn't available but was latter defined
123 | if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
124 | cachedSetTimeout = setTimeout;
125 | return setTimeout(fun, 0);
126 | }
127 | try {
128 | // when when somebody has screwed with setTimeout but no I.E. maddness
129 | return cachedSetTimeout(fun, 0);
130 | } catch(e){
131 | try {
132 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
133 | return cachedSetTimeout.call(null, fun, 0);
134 | } catch(e){
135 | // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
136 | return cachedSetTimeout.call(this, fun, 0);
137 | }
138 | }
139 |
140 |
141 | }
142 | function runClearTimeout(marker) {
143 | if (cachedClearTimeout === clearTimeout) {
144 | //normal enviroments in sane situations
145 | return clearTimeout(marker);
146 | }
147 | // if clearTimeout wasn't available but was latter defined
148 | if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
149 | cachedClearTimeout = clearTimeout;
150 | return clearTimeout(marker);
151 | }
152 | try {
153 | // when when somebody has screwed with setTimeout but no I.E. maddness
154 | return cachedClearTimeout(marker);
155 | } catch (e){
156 | try {
157 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
158 | return cachedClearTimeout.call(null, marker);
159 | } catch (e){
160 | // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
161 | // Some versions of I.E. have different rules for clearTimeout vs setTimeout
162 | return cachedClearTimeout.call(this, marker);
163 | }
164 | }
165 |
166 |
167 |
168 | }
169 | var queue = [];
170 | var draining = false;
171 | var currentQueue;
172 | var queueIndex = -1;
173 |
174 | function cleanUpNextTick() {
175 | if (!draining || !currentQueue) {
176 | return;
177 | }
178 | draining = false;
179 | if (currentQueue.length) {
180 | queue = currentQueue.concat(queue);
181 | } else {
182 | queueIndex = -1;
183 | }
184 | if (queue.length) {
185 | drainQueue();
186 | }
187 | }
188 |
189 | function drainQueue() {
190 | if (draining) {
191 | return;
192 | }
193 | var timeout = runTimeout(cleanUpNextTick);
194 | draining = true;
195 |
196 | var len = queue.length;
197 | while(len) {
198 | currentQueue = queue;
199 | queue = [];
200 | while (++queueIndex < len) {
201 | if (currentQueue) {
202 | currentQueue[queueIndex].run();
203 | }
204 | }
205 | queueIndex = -1;
206 | len = queue.length;
207 | }
208 | currentQueue = null;
209 | draining = false;
210 | runClearTimeout(timeout);
211 | }
212 |
213 | process.nextTick = function (fun) {
214 | var args = new Array(arguments.length - 1);
215 | if (arguments.length > 1) {
216 | for (var i = 1; i < arguments.length; i++) {
217 | args[i - 1] = arguments[i];
218 | }
219 | }
220 | queue.push(new Item(fun, args));
221 | if (queue.length === 1 && !draining) {
222 | runTimeout(drainQueue);
223 | }
224 | };
225 |
226 | // v8 likes predictible objects
227 | function Item(fun, array) {
228 | this.fun = fun;
229 | this.array = array;
230 | }
231 | Item.prototype.run = function () {
232 | this.fun.apply(null, this.array);
233 | };
234 | process.title = 'browser';
235 | process.browser = true;
236 | process.env = {};
237 | process.argv = [];
238 | process.version = ''; // empty string to avoid regexp issues
239 | process.versions = {};
240 |
241 | function noop() {}
242 |
243 | process.on = noop;
244 | process.addListener = noop;
245 | process.once = noop;
246 | process.off = noop;
247 | process.removeListener = noop;
248 | process.removeAllListeners = noop;
249 | process.emit = noop;
250 | process.prependListener = noop;
251 | process.prependOnceListener = noop;
252 |
253 | process.listeners = function (name) { return [] }
254 |
255 | process.binding = function (name) {
256 | throw new Error('process.binding is not supported');
257 | };
258 |
259 | process.cwd = function () { return '/' };
260 | process.chdir = function (dir) {
261 | throw new Error('process.chdir is not supported');
262 | };
263 | process.umask = function() { return 0; };
264 |
265 |
266 | /***/ }),
267 | /* 1 */
268 | /***/ (function(module, exports, __webpack_require__) {
269 |
270 | "use strict";
271 |
272 |
273 | /**
274 | * Copyright (c) 2013-present, Facebook, Inc.
275 | *
276 | * This source code is licensed under the MIT license found in the
277 | * LICENSE file in the root directory of this source tree.
278 | *
279 | *
280 | */
281 |
282 | function makeEmptyFunction(arg) {
283 | return function () {
284 | return arg;
285 | };
286 | }
287 |
288 | /**
289 | * This function accepts and discards inputs; it has no side effects. This is
290 | * primarily useful idiomatically for overridable function endpoints which
291 | * always need to be callable, since JS lacks a null-call idiom ala Cocoa.
292 | */
293 | var emptyFunction = function emptyFunction() {};
294 |
295 | emptyFunction.thatReturns = makeEmptyFunction;
296 | emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
297 | emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
298 | emptyFunction.thatReturnsNull = makeEmptyFunction(null);
299 | emptyFunction.thatReturnsThis = function () {
300 | return this;
301 | };
302 | emptyFunction.thatReturnsArgument = function (arg) {
303 | return arg;
304 | };
305 |
306 | module.exports = emptyFunction;
307 |
308 | /***/ }),
309 | /* 2 */
310 | /***/ (function(module, exports, __webpack_require__) {
311 |
312 | "use strict";
313 | /* WEBPACK VAR INJECTION */(function(process) {/**
314 | * Copyright (c) 2013-present, Facebook, Inc.
315 | *
316 | * This source code is licensed under the MIT license found in the
317 | * LICENSE file in the root directory of this source tree.
318 | *
319 | */
320 |
321 |
322 |
323 | /**
324 | * Use invariant() to assert state which your program assumes to be true.
325 | *
326 | * Provide sprintf-style format (only %s is supported) and arguments
327 | * to provide information about what broke and what you were
328 | * expecting.
329 | *
330 | * The invariant message will be stripped in production, but the invariant
331 | * will remain to ensure logic does not differ in production.
332 | */
333 |
334 | var validateFormat = function validateFormat(format) {};
335 |
336 | if (process.env.NODE_ENV !== 'production') {
337 | validateFormat = function validateFormat(format) {
338 | if (format === undefined) {
339 | throw new Error('invariant requires an error message argument');
340 | }
341 | };
342 | }
343 |
344 | function invariant(condition, format, a, b, c, d, e, f) {
345 | validateFormat(format);
346 |
347 | if (!condition) {
348 | var error;
349 | if (format === undefined) {
350 | error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
351 | } else {
352 | var args = [a, b, c, d, e, f];
353 | var argIndex = 0;
354 | error = new Error(format.replace(/%s/g, function () {
355 | return args[argIndex++];
356 | }));
357 | error.name = 'Invariant Violation';
358 | }
359 |
360 | error.framesToPop = 1; // we don't care about invariant's own frame
361 | throw error;
362 | }
363 | }
364 |
365 | module.exports = invariant;
366 | /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
367 |
368 | /***/ }),
369 | /* 3 */
370 | /***/ (function(module, exports, __webpack_require__) {
371 |
372 | "use strict";
373 | /**
374 | * Copyright (c) 2013-present, Facebook, Inc.
375 | *
376 | * This source code is licensed under the MIT license found in the
377 | * LICENSE file in the root directory of this source tree.
378 | */
379 |
380 |
381 |
382 | var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
383 |
384 | module.exports = ReactPropTypesSecret;
385 |
386 |
387 | /***/ }),
388 | /* 4 */
389 | /***/ (function(module, exports, __webpack_require__) {
390 |
391 | "use strict";
392 | /* WEBPACK VAR INJECTION */(function(process) {/**
393 | * Copyright (c) 2014-present, Facebook, Inc.
394 | *
395 | * This source code is licensed under the MIT license found in the
396 | * LICENSE file in the root directory of this source tree.
397 | *
398 | */
399 |
400 |
401 |
402 | var emptyFunction = __webpack_require__(1);
403 |
404 | /**
405 | * Similar to invariant but only logs a warning if the condition is not met.
406 | * This can be used to log issues in development environments in critical
407 | * paths. Removing the logging code for production environments will keep the
408 | * same logic and follow the same code paths.
409 | */
410 |
411 | var warning = emptyFunction;
412 |
413 | if (process.env.NODE_ENV !== 'production') {
414 | var printWarning = function printWarning(format) {
415 | for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
416 | args[_key - 1] = arguments[_key];
417 | }
418 |
419 | var argIndex = 0;
420 | var message = 'Warning: ' + format.replace(/%s/g, function () {
421 | return args[argIndex++];
422 | });
423 | if (typeof console !== 'undefined') {
424 | console.error(message);
425 | }
426 | try {
427 | // --- Welcome to debugging React ---
428 | // This error was thrown as a convenience so that you can use this stack
429 | // to find the callsite that caused this warning to fire.
430 | throw new Error(message);
431 | } catch (x) {}
432 | };
433 |
434 | warning = function warning(condition, format) {
435 | if (format === undefined) {
436 | throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
437 | }
438 |
439 | if (format.indexOf('Failed Composite propType: ') === 0) {
440 | return; // Ignore CompositeComponent proptype check.
441 | }
442 |
443 | if (!condition) {
444 | for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
445 | args[_key2 - 2] = arguments[_key2];
446 | }
447 |
448 | printWarning.apply(undefined, [format].concat(args));
449 | }
450 | };
451 | }
452 |
453 | module.exports = warning;
454 | /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
455 |
456 | /***/ }),
457 | /* 5 */
458 | /***/ (function(module, exports, __webpack_require__) {
459 |
460 | "use strict";
461 |
462 |
463 | Object.defineProperty(exports, "__esModule", {
464 | value: true
465 | });
466 |
467 | var _SortableComposition = __webpack_require__(6);
468 |
469 | Object.defineProperty(exports, 'sortable', {
470 | enumerable: true,
471 | get: function get() {
472 | return _SortableComposition.SortableComposition;
473 | }
474 | });
475 | Object.defineProperty(exports, 'Sortable', {
476 | enumerable: true,
477 | get: function get() {
478 | return _SortableComposition.SortableComposition;
479 | }
480 | });
481 | Object.defineProperty(exports, 'HORIZONTAL', {
482 | enumerable: true,
483 | get: function get() {
484 | return _SortableComposition.HORIZONTAL;
485 | }
486 | });
487 | Object.defineProperty(exports, 'VERTICAL', {
488 | enumerable: true,
489 | get: function get() {
490 | return _SortableComposition.VERTICAL;
491 | }
492 | });
493 |
494 | /***/ }),
495 | /* 6 */
496 | /***/ (function(module, exports, __webpack_require__) {
497 |
498 | "use strict";
499 |
500 |
501 | Object.defineProperty(exports, "__esModule", {
502 | value: true
503 | });
504 | exports.HORIZONTAL = exports.VERTICAL = undefined;
505 |
506 | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
507 |
508 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
509 |
510 | exports.SortableComposition = SortableComposition;
511 |
512 | var _react = __webpack_require__(7);
513 |
514 | var _react2 = _interopRequireDefault(_react);
515 |
516 | var _propTypes = __webpack_require__(8);
517 |
518 | var _propTypes2 = _interopRequireDefault(_propTypes);
519 |
520 | var _helpers = __webpack_require__(13);
521 |
522 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
523 |
524 | function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
525 |
526 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
527 |
528 | function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
529 |
530 | function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
531 |
532 | var VERTICAL = exports.VERTICAL = 'VERTICAL';
533 | var HORIZONTAL = exports.HORIZONTAL = 'HORIZONTAL';
534 |
535 | /*** Higher-order component - this component works like a factory for draggable items */
536 |
537 | var draggingIndex = null;
538 |
539 | function SortableComposition(Component) {
540 | var flowDirection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : VERTICAL;
541 |
542 |
543 | return function (_React$Component) {
544 | _inherits(Sortable, _React$Component);
545 |
546 | function Sortable() {
547 | var _ref;
548 |
549 | var _temp, _this, _ret;
550 |
551 | _classCallCheck(this, Sortable);
552 |
553 | for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
554 | args[_key] = arguments[_key];
555 | }
556 |
557 | return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Sortable.__proto__ || Object.getPrototypeOf(Sortable)).call.apply(_ref, [this].concat(args))), _this), _this.sortEnd = function (e) {
558 | e.preventDefault();
559 | draggingIndex = null;
560 | }, _this.sortStart = function (e) {
561 | draggingIndex = e.currentTarget.dataset.id;
562 | var dt = e.dataTransfer;
563 | if (dt !== undefined) {
564 | e.dataTransfer.setData('text', e.target.innerHTML);
565 |
566 | //fix http://stackoverflow.com/questions/27656183/preserve-appearance-of-dragged-a-element-when-using-html5-draggable-attribute
567 | if (dt.setDragImage && e.currentTarget.tagName.toLowerCase() === 'a') {
568 | dt.setDragImage(e.target, 0, 0);
569 | }
570 | }
571 | }, _this.dragOver = function (e) {
572 | e.preventDefault();
573 | var _this$props = _this.props,
574 | moveInMiddle = _this$props.moveInMiddle,
575 | sortId = _this$props.sortId;
576 |
577 | var overEl = e.currentTarget; //underlying element
578 | var indexDragged = Number(overEl.dataset.id); //index of underlying element in the set DOM elements
579 | var indexFrom = Number(draggingIndex);
580 | var height = overEl.getBoundingClientRect().height;
581 | var width = overEl.getBoundingClientRect().width;
582 | var positionX = e.clientX;
583 | var positionY = e.clientY;
584 | var topOffset = overEl.getBoundingClientRect().top;
585 | var leftOffset = overEl.getBoundingClientRect().left;
586 | var mouseBeyond = void 0;
587 | var items = _this.props.items;
588 |
589 |
590 | if (flowDirection === VERTICAL) {
591 | mouseBeyond = (0, _helpers.isMouseBeyond)(positionY, topOffset, height, moveInMiddle);
592 | }
593 |
594 | if (flowDirection === HORIZONTAL) {
595 | mouseBeyond = (0, _helpers.isMouseBeyond)(positionX, leftOffset, width, moveInMiddle);
596 | }
597 |
598 | var shouldSwapItems = _helpers.isMouseBeyond && indexDragged !== indexFrom;
599 |
600 | if (indexDragged !== indexFrom && mouseBeyond) {
601 | items = (0, _helpers.swapArrayElements)(items, indexFrom, indexDragged);
602 | draggingIndex = indexDragged;
603 | _this.props.onSortItems(items);
604 | }
605 | }, _temp), _possibleConstructorReturn(_this, _ret);
606 | }
607 |
608 | _createClass(Sortable, [{
609 | key: 'render',
610 | value: function render() {
611 | var newProps = Object.assign({}, this.props);
612 | delete newProps.onSortItems;
613 |
614 | var sortId = newProps.sortId,
615 | props = _objectWithoutProperties(newProps, ['sortId']);
616 |
617 | return _react2.default.createElement(Component, _extends({
618 | draggable: true,
619 | onDragOver: this.dragOver,
620 | onDragStart: this.sortStart,
621 | onDragEnd: this.sortEnd,
622 | onTouchStart: this.sortStart,
623 | onTouchMove: this.dragOver,
624 | onTouchEnd: this.sortEnd,
625 | 'data-id': sortId
626 | }, props));
627 | }
628 | }]);
629 |
630 | return Sortable;
631 | }(_react2.default.Component);
632 |
633 | Sortable.propTypes = {
634 | items: _propTypes2.default.array.isRequired,
635 | onSortItems: _propTypes2.default.func.isRequired,
636 | sortId: _propTypes2.default.number
637 | };
638 |
639 | Sortable.defaultProps = {
640 | moveInMiddle: false
641 | };
642 |
643 | return Sortable;
644 | }
645 |
646 | /***/ }),
647 | /* 7 */
648 | /***/ (function(module, exports) {
649 |
650 | module.exports = __WEBPACK_EXTERNAL_MODULE_7__;
651 |
652 | /***/ }),
653 | /* 8 */
654 | /***/ (function(module, exports, __webpack_require__) {
655 |
656 | /* WEBPACK VAR INJECTION */(function(process) {/**
657 | * Copyright (c) 2013-present, Facebook, Inc.
658 | *
659 | * This source code is licensed under the MIT license found in the
660 | * LICENSE file in the root directory of this source tree.
661 | */
662 |
663 | if (process.env.NODE_ENV !== 'production') {
664 | var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
665 | Symbol.for &&
666 | Symbol.for('react.element')) ||
667 | 0xeac7;
668 |
669 | var isValidElement = function(object) {
670 | return typeof object === 'object' &&
671 | object !== null &&
672 | object.$$typeof === REACT_ELEMENT_TYPE;
673 | };
674 |
675 | // By explicitly using `prop-types` you are opting into new development behavior.
676 | // http://fb.me/prop-types-in-prod
677 | var throwOnDirectAccess = true;
678 | module.exports = __webpack_require__(9)(isValidElement, throwOnDirectAccess);
679 | } else {
680 | // By explicitly using `prop-types` you are opting into new production behavior.
681 | // http://fb.me/prop-types-in-prod
682 | module.exports = __webpack_require__(12)();
683 | }
684 |
685 | /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
686 |
687 | /***/ }),
688 | /* 9 */
689 | /***/ (function(module, exports, __webpack_require__) {
690 |
691 | "use strict";
692 | /* WEBPACK VAR INJECTION */(function(process) {/**
693 | * Copyright (c) 2013-present, Facebook, Inc.
694 | *
695 | * This source code is licensed under the MIT license found in the
696 | * LICENSE file in the root directory of this source tree.
697 | */
698 |
699 |
700 |
701 | var emptyFunction = __webpack_require__(1);
702 | var invariant = __webpack_require__(2);
703 | var warning = __webpack_require__(4);
704 | var assign = __webpack_require__(10);
705 |
706 | var ReactPropTypesSecret = __webpack_require__(3);
707 | var checkPropTypes = __webpack_require__(11);
708 |
709 | module.exports = function(isValidElement, throwOnDirectAccess) {
710 | /* global Symbol */
711 | var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
712 | var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
713 |
714 | /**
715 | * Returns the iterator method function contained on the iterable object.
716 | *
717 | * Be sure to invoke the function with the iterable as context:
718 | *
719 | * var iteratorFn = getIteratorFn(myIterable);
720 | * if (iteratorFn) {
721 | * var iterator = iteratorFn.call(myIterable);
722 | * ...
723 | * }
724 | *
725 | * @param {?object} maybeIterable
726 | * @return {?function}
727 | */
728 | function getIteratorFn(maybeIterable) {
729 | var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
730 | if (typeof iteratorFn === 'function') {
731 | return iteratorFn;
732 | }
733 | }
734 |
735 | /**
736 | * Collection of methods that allow declaration and validation of props that are
737 | * supplied to React components. Example usage:
738 | *
739 | * var Props = require('ReactPropTypes');
740 | * var MyArticle = React.createClass({
741 | * propTypes: {
742 | * // An optional string prop named "description".
743 | * description: Props.string,
744 | *
745 | * // A required enum prop named "category".
746 | * category: Props.oneOf(['News','Photos']).isRequired,
747 | *
748 | * // A prop named "dialog" that requires an instance of Dialog.
749 | * dialog: Props.instanceOf(Dialog).isRequired
750 | * },
751 | * render: function() { ... }
752 | * });
753 | *
754 | * A more formal specification of how these methods are used:
755 | *
756 | * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
757 | * decl := ReactPropTypes.{type}(.isRequired)?
758 | *
759 | * Each and every declaration produces a function with the same signature. This
760 | * allows the creation of custom validation functions. For example:
761 | *
762 | * var MyLink = React.createClass({
763 | * propTypes: {
764 | * // An optional string or URI prop named "href".
765 | * href: function(props, propName, componentName) {
766 | * var propValue = props[propName];
767 | * if (propValue != null && typeof propValue !== 'string' &&
768 | * !(propValue instanceof URI)) {
769 | * return new Error(
770 | * 'Expected a string or an URI for ' + propName + ' in ' +
771 | * componentName
772 | * );
773 | * }
774 | * }
775 | * },
776 | * render: function() {...}
777 | * });
778 | *
779 | * @internal
780 | */
781 |
782 | var ANONYMOUS = '<>';
783 |
784 | // Important!
785 | // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
786 | var ReactPropTypes = {
787 | array: createPrimitiveTypeChecker('array'),
788 | bool: createPrimitiveTypeChecker('boolean'),
789 | func: createPrimitiveTypeChecker('function'),
790 | number: createPrimitiveTypeChecker('number'),
791 | object: createPrimitiveTypeChecker('object'),
792 | string: createPrimitiveTypeChecker('string'),
793 | symbol: createPrimitiveTypeChecker('symbol'),
794 |
795 | any: createAnyTypeChecker(),
796 | arrayOf: createArrayOfTypeChecker,
797 | element: createElementTypeChecker(),
798 | instanceOf: createInstanceTypeChecker,
799 | node: createNodeChecker(),
800 | objectOf: createObjectOfTypeChecker,
801 | oneOf: createEnumTypeChecker,
802 | oneOfType: createUnionTypeChecker,
803 | shape: createShapeTypeChecker,
804 | exact: createStrictShapeTypeChecker,
805 | };
806 |
807 | /**
808 | * inlined Object.is polyfill to avoid requiring consumers ship their own
809 | * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
810 | */
811 | /*eslint-disable no-self-compare*/
812 | function is(x, y) {
813 | // SameValue algorithm
814 | if (x === y) {
815 | // Steps 1-5, 7-10
816 | // Steps 6.b-6.e: +0 != -0
817 | return x !== 0 || 1 / x === 1 / y;
818 | } else {
819 | // Step 6.a: NaN == NaN
820 | return x !== x && y !== y;
821 | }
822 | }
823 | /*eslint-enable no-self-compare*/
824 |
825 | /**
826 | * We use an Error-like object for backward compatibility as people may call
827 | * PropTypes directly and inspect their output. However, we don't use real
828 | * Errors anymore. We don't inspect their stack anyway, and creating them
829 | * is prohibitively expensive if they are created too often, such as what
830 | * happens in oneOfType() for any type before the one that matched.
831 | */
832 | function PropTypeError(message) {
833 | this.message = message;
834 | this.stack = '';
835 | }
836 | // Make `instanceof Error` still work for returned errors.
837 | PropTypeError.prototype = Error.prototype;
838 |
839 | function createChainableTypeChecker(validate) {
840 | if (process.env.NODE_ENV !== 'production') {
841 | var manualPropTypeCallCache = {};
842 | var manualPropTypeWarningCount = 0;
843 | }
844 | function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
845 | componentName = componentName || ANONYMOUS;
846 | propFullName = propFullName || propName;
847 |
848 | if (secret !== ReactPropTypesSecret) {
849 | if (throwOnDirectAccess) {
850 | // New behavior only for users of `prop-types` package
851 | invariant(
852 | false,
853 | 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
854 | 'Use `PropTypes.checkPropTypes()` to call them. ' +
855 | 'Read more at http://fb.me/use-check-prop-types'
856 | );
857 | } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {
858 | // Old behavior for people using React.PropTypes
859 | var cacheKey = componentName + ':' + propName;
860 | if (
861 | !manualPropTypeCallCache[cacheKey] &&
862 | // Avoid spamming the console because they are often not actionable except for lib authors
863 | manualPropTypeWarningCount < 3
864 | ) {
865 | warning(
866 | false,
867 | 'You are manually calling a React.PropTypes validation ' +
868 | 'function for the `%s` prop on `%s`. This is deprecated ' +
869 | 'and will throw in the standalone `prop-types` package. ' +
870 | 'You may be seeing this warning due to a third-party PropTypes ' +
871 | 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
872 | propFullName,
873 | componentName
874 | );
875 | manualPropTypeCallCache[cacheKey] = true;
876 | manualPropTypeWarningCount++;
877 | }
878 | }
879 | }
880 | if (props[propName] == null) {
881 | if (isRequired) {
882 | if (props[propName] === null) {
883 | return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
884 | }
885 | return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
886 | }
887 | return null;
888 | } else {
889 | return validate(props, propName, componentName, location, propFullName);
890 | }
891 | }
892 |
893 | var chainedCheckType = checkType.bind(null, false);
894 | chainedCheckType.isRequired = checkType.bind(null, true);
895 |
896 | return chainedCheckType;
897 | }
898 |
899 | function createPrimitiveTypeChecker(expectedType) {
900 | function validate(props, propName, componentName, location, propFullName, secret) {
901 | var propValue = props[propName];
902 | var propType = getPropType(propValue);
903 | if (propType !== expectedType) {
904 | // `propValue` being instance of, say, date/regexp, pass the 'object'
905 | // check, but we can offer a more precise error message here rather than
906 | // 'of type `object`'.
907 | var preciseType = getPreciseType(propValue);
908 |
909 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
910 | }
911 | return null;
912 | }
913 | return createChainableTypeChecker(validate);
914 | }
915 |
916 | function createAnyTypeChecker() {
917 | return createChainableTypeChecker(emptyFunction.thatReturnsNull);
918 | }
919 |
920 | function createArrayOfTypeChecker(typeChecker) {
921 | function validate(props, propName, componentName, location, propFullName) {
922 | if (typeof typeChecker !== 'function') {
923 | return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
924 | }
925 | var propValue = props[propName];
926 | if (!Array.isArray(propValue)) {
927 | var propType = getPropType(propValue);
928 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
929 | }
930 | for (var i = 0; i < propValue.length; i++) {
931 | var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
932 | if (error instanceof Error) {
933 | return error;
934 | }
935 | }
936 | return null;
937 | }
938 | return createChainableTypeChecker(validate);
939 | }
940 |
941 | function createElementTypeChecker() {
942 | function validate(props, propName, componentName, location, propFullName) {
943 | var propValue = props[propName];
944 | if (!isValidElement(propValue)) {
945 | var propType = getPropType(propValue);
946 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
947 | }
948 | return null;
949 | }
950 | return createChainableTypeChecker(validate);
951 | }
952 |
953 | function createInstanceTypeChecker(expectedClass) {
954 | function validate(props, propName, componentName, location, propFullName) {
955 | if (!(props[propName] instanceof expectedClass)) {
956 | var expectedClassName = expectedClass.name || ANONYMOUS;
957 | var actualClassName = getClassName(props[propName]);
958 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
959 | }
960 | return null;
961 | }
962 | return createChainableTypeChecker(validate);
963 | }
964 |
965 | function createEnumTypeChecker(expectedValues) {
966 | if (!Array.isArray(expectedValues)) {
967 | process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
968 | return emptyFunction.thatReturnsNull;
969 | }
970 |
971 | function validate(props, propName, componentName, location, propFullName) {
972 | var propValue = props[propName];
973 | for (var i = 0; i < expectedValues.length; i++) {
974 | if (is(propValue, expectedValues[i])) {
975 | return null;
976 | }
977 | }
978 |
979 | var valuesString = JSON.stringify(expectedValues);
980 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
981 | }
982 | return createChainableTypeChecker(validate);
983 | }
984 |
985 | function createObjectOfTypeChecker(typeChecker) {
986 | function validate(props, propName, componentName, location, propFullName) {
987 | if (typeof typeChecker !== 'function') {
988 | return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
989 | }
990 | var propValue = props[propName];
991 | var propType = getPropType(propValue);
992 | if (propType !== 'object') {
993 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
994 | }
995 | for (var key in propValue) {
996 | if (propValue.hasOwnProperty(key)) {
997 | var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
998 | if (error instanceof Error) {
999 | return error;
1000 | }
1001 | }
1002 | }
1003 | return null;
1004 | }
1005 | return createChainableTypeChecker(validate);
1006 | }
1007 |
1008 | function createUnionTypeChecker(arrayOfTypeCheckers) {
1009 | if (!Array.isArray(arrayOfTypeCheckers)) {
1010 | process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
1011 | return emptyFunction.thatReturnsNull;
1012 | }
1013 |
1014 | for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
1015 | var checker = arrayOfTypeCheckers[i];
1016 | if (typeof checker !== 'function') {
1017 | warning(
1018 | false,
1019 | 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
1020 | 'received %s at index %s.',
1021 | getPostfixForTypeWarning(checker),
1022 | i
1023 | );
1024 | return emptyFunction.thatReturnsNull;
1025 | }
1026 | }
1027 |
1028 | function validate(props, propName, componentName, location, propFullName) {
1029 | for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
1030 | var checker = arrayOfTypeCheckers[i];
1031 | if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
1032 | return null;
1033 | }
1034 | }
1035 |
1036 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
1037 | }
1038 | return createChainableTypeChecker(validate);
1039 | }
1040 |
1041 | function createNodeChecker() {
1042 | function validate(props, propName, componentName, location, propFullName) {
1043 | if (!isNode(props[propName])) {
1044 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
1045 | }
1046 | return null;
1047 | }
1048 | return createChainableTypeChecker(validate);
1049 | }
1050 |
1051 | function createShapeTypeChecker(shapeTypes) {
1052 | function validate(props, propName, componentName, location, propFullName) {
1053 | var propValue = props[propName];
1054 | var propType = getPropType(propValue);
1055 | if (propType !== 'object') {
1056 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
1057 | }
1058 | for (var key in shapeTypes) {
1059 | var checker = shapeTypes[key];
1060 | if (!checker) {
1061 | continue;
1062 | }
1063 | var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
1064 | if (error) {
1065 | return error;
1066 | }
1067 | }
1068 | return null;
1069 | }
1070 | return createChainableTypeChecker(validate);
1071 | }
1072 |
1073 | function createStrictShapeTypeChecker(shapeTypes) {
1074 | function validate(props, propName, componentName, location, propFullName) {
1075 | var propValue = props[propName];
1076 | var propType = getPropType(propValue);
1077 | if (propType !== 'object') {
1078 | return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
1079 | }
1080 | // We need to check all keys in case some are required but missing from
1081 | // props.
1082 | var allKeys = assign({}, props[propName], shapeTypes);
1083 | for (var key in allKeys) {
1084 | var checker = shapeTypes[key];
1085 | if (!checker) {
1086 | return new PropTypeError(
1087 | 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
1088 | '\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
1089 | '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
1090 | );
1091 | }
1092 | var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
1093 | if (error) {
1094 | return error;
1095 | }
1096 | }
1097 | return null;
1098 | }
1099 |
1100 | return createChainableTypeChecker(validate);
1101 | }
1102 |
1103 | function isNode(propValue) {
1104 | switch (typeof propValue) {
1105 | case 'number':
1106 | case 'string':
1107 | case 'undefined':
1108 | return true;
1109 | case 'boolean':
1110 | return !propValue;
1111 | case 'object':
1112 | if (Array.isArray(propValue)) {
1113 | return propValue.every(isNode);
1114 | }
1115 | if (propValue === null || isValidElement(propValue)) {
1116 | return true;
1117 | }
1118 |
1119 | var iteratorFn = getIteratorFn(propValue);
1120 | if (iteratorFn) {
1121 | var iterator = iteratorFn.call(propValue);
1122 | var step;
1123 | if (iteratorFn !== propValue.entries) {
1124 | while (!(step = iterator.next()).done) {
1125 | if (!isNode(step.value)) {
1126 | return false;
1127 | }
1128 | }
1129 | } else {
1130 | // Iterator will provide entry [k,v] tuples rather than values.
1131 | while (!(step = iterator.next()).done) {
1132 | var entry = step.value;
1133 | if (entry) {
1134 | if (!isNode(entry[1])) {
1135 | return false;
1136 | }
1137 | }
1138 | }
1139 | }
1140 | } else {
1141 | return false;
1142 | }
1143 |
1144 | return true;
1145 | default:
1146 | return false;
1147 | }
1148 | }
1149 |
1150 | function isSymbol(propType, propValue) {
1151 | // Native Symbol.
1152 | if (propType === 'symbol') {
1153 | return true;
1154 | }
1155 |
1156 | // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
1157 | if (propValue['@@toStringTag'] === 'Symbol') {
1158 | return true;
1159 | }
1160 |
1161 | // Fallback for non-spec compliant Symbols which are polyfilled.
1162 | if (typeof Symbol === 'function' && propValue instanceof Symbol) {
1163 | return true;
1164 | }
1165 |
1166 | return false;
1167 | }
1168 |
1169 | // Equivalent of `typeof` but with special handling for array and regexp.
1170 | function getPropType(propValue) {
1171 | var propType = typeof propValue;
1172 | if (Array.isArray(propValue)) {
1173 | return 'array';
1174 | }
1175 | if (propValue instanceof RegExp) {
1176 | // Old webkits (at least until Android 4.0) return 'function' rather than
1177 | // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
1178 | // passes PropTypes.object.
1179 | return 'object';
1180 | }
1181 | if (isSymbol(propType, propValue)) {
1182 | return 'symbol';
1183 | }
1184 | return propType;
1185 | }
1186 |
1187 | // This handles more types than `getPropType`. Only used for error messages.
1188 | // See `createPrimitiveTypeChecker`.
1189 | function getPreciseType(propValue) {
1190 | if (typeof propValue === 'undefined' || propValue === null) {
1191 | return '' + propValue;
1192 | }
1193 | var propType = getPropType(propValue);
1194 | if (propType === 'object') {
1195 | if (propValue instanceof Date) {
1196 | return 'date';
1197 | } else if (propValue instanceof RegExp) {
1198 | return 'regexp';
1199 | }
1200 | }
1201 | return propType;
1202 | }
1203 |
1204 | // Returns a string that is postfixed to a warning about an invalid type.
1205 | // For example, "undefined" or "of type array"
1206 | function getPostfixForTypeWarning(value) {
1207 | var type = getPreciseType(value);
1208 | switch (type) {
1209 | case 'array':
1210 | case 'object':
1211 | return 'an ' + type;
1212 | case 'boolean':
1213 | case 'date':
1214 | case 'regexp':
1215 | return 'a ' + type;
1216 | default:
1217 | return type;
1218 | }
1219 | }
1220 |
1221 | // Returns class name of the object, if any.
1222 | function getClassName(propValue) {
1223 | if (!propValue.constructor || !propValue.constructor.name) {
1224 | return ANONYMOUS;
1225 | }
1226 | return propValue.constructor.name;
1227 | }
1228 |
1229 | ReactPropTypes.checkPropTypes = checkPropTypes;
1230 | ReactPropTypes.PropTypes = ReactPropTypes;
1231 |
1232 | return ReactPropTypes;
1233 | };
1234 |
1235 | /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
1236 |
1237 | /***/ }),
1238 | /* 10 */
1239 | /***/ (function(module, exports, __webpack_require__) {
1240 |
1241 | "use strict";
1242 | /*
1243 | object-assign
1244 | (c) Sindre Sorhus
1245 | @license MIT
1246 | */
1247 |
1248 |
1249 | /* eslint-disable no-unused-vars */
1250 | var getOwnPropertySymbols = Object.getOwnPropertySymbols;
1251 | var hasOwnProperty = Object.prototype.hasOwnProperty;
1252 | var propIsEnumerable = Object.prototype.propertyIsEnumerable;
1253 |
1254 | function toObject(val) {
1255 | if (val === null || val === undefined) {
1256 | throw new TypeError('Object.assign cannot be called with null or undefined');
1257 | }
1258 |
1259 | return Object(val);
1260 | }
1261 |
1262 | function shouldUseNative() {
1263 | try {
1264 | if (!Object.assign) {
1265 | return false;
1266 | }
1267 |
1268 | // Detect buggy property enumeration order in older V8 versions.
1269 |
1270 | // https://bugs.chromium.org/p/v8/issues/detail?id=4118
1271 | var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
1272 | test1[5] = 'de';
1273 | if (Object.getOwnPropertyNames(test1)[0] === '5') {
1274 | return false;
1275 | }
1276 |
1277 | // https://bugs.chromium.org/p/v8/issues/detail?id=3056
1278 | var test2 = {};
1279 | for (var i = 0; i < 10; i++) {
1280 | test2['_' + String.fromCharCode(i)] = i;
1281 | }
1282 | var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
1283 | return test2[n];
1284 | });
1285 | if (order2.join('') !== '0123456789') {
1286 | return false;
1287 | }
1288 |
1289 | // https://bugs.chromium.org/p/v8/issues/detail?id=3056
1290 | var test3 = {};
1291 | 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
1292 | test3[letter] = letter;
1293 | });
1294 | if (Object.keys(Object.assign({}, test3)).join('') !==
1295 | 'abcdefghijklmnopqrst') {
1296 | return false;
1297 | }
1298 |
1299 | return true;
1300 | } catch (err) {
1301 | // We don't expect any of the above to throw, but better to be safe.
1302 | return false;
1303 | }
1304 | }
1305 |
1306 | module.exports = shouldUseNative() ? Object.assign : function (target, source) {
1307 | var from;
1308 | var to = toObject(target);
1309 | var symbols;
1310 |
1311 | for (var s = 1; s < arguments.length; s++) {
1312 | from = Object(arguments[s]);
1313 |
1314 | for (var key in from) {
1315 | if (hasOwnProperty.call(from, key)) {
1316 | to[key] = from[key];
1317 | }
1318 | }
1319 |
1320 | if (getOwnPropertySymbols) {
1321 | symbols = getOwnPropertySymbols(from);
1322 | for (var i = 0; i < symbols.length; i++) {
1323 | if (propIsEnumerable.call(from, symbols[i])) {
1324 | to[symbols[i]] = from[symbols[i]];
1325 | }
1326 | }
1327 | }
1328 | }
1329 |
1330 | return to;
1331 | };
1332 |
1333 |
1334 | /***/ }),
1335 | /* 11 */
1336 | /***/ (function(module, exports, __webpack_require__) {
1337 |
1338 | "use strict";
1339 | /* WEBPACK VAR INJECTION */(function(process) {/**
1340 | * Copyright (c) 2013-present, Facebook, Inc.
1341 | *
1342 | * This source code is licensed under the MIT license found in the
1343 | * LICENSE file in the root directory of this source tree.
1344 | */
1345 |
1346 |
1347 |
1348 | if (process.env.NODE_ENV !== 'production') {
1349 | var invariant = __webpack_require__(2);
1350 | var warning = __webpack_require__(4);
1351 | var ReactPropTypesSecret = __webpack_require__(3);
1352 | var loggedTypeFailures = {};
1353 | }
1354 |
1355 | /**
1356 | * Assert that the values match with the type specs.
1357 | * Error messages are memorized and will only be shown once.
1358 | *
1359 | * @param {object} typeSpecs Map of name to a ReactPropType
1360 | * @param {object} values Runtime values that need to be type-checked
1361 | * @param {string} location e.g. "prop", "context", "child context"
1362 | * @param {string} componentName Name of the component for error messages.
1363 | * @param {?Function} getStack Returns the component stack.
1364 | * @private
1365 | */
1366 | function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
1367 | if (process.env.NODE_ENV !== 'production') {
1368 | for (var typeSpecName in typeSpecs) {
1369 | if (typeSpecs.hasOwnProperty(typeSpecName)) {
1370 | var error;
1371 | // Prop type validation may throw. In case they do, we don't want to
1372 | // fail the render phase where it didn't fail before. So we log it.
1373 | // After these have been cleaned up, we'll let them throw.
1374 | try {
1375 | // This is intentionally an invariant that gets caught. It's the same
1376 | // behavior as without this statement except with a better message.
1377 | invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
1378 | error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
1379 | } catch (ex) {
1380 | error = ex;
1381 | }
1382 | warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
1383 | if (error instanceof Error && !(error.message in loggedTypeFailures)) {
1384 | // Only monitor this failure once because there tends to be a lot of the
1385 | // same error.
1386 | loggedTypeFailures[error.message] = true;
1387 |
1388 | var stack = getStack ? getStack() : '';
1389 |
1390 | warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
1391 | }
1392 | }
1393 | }
1394 | }
1395 | }
1396 |
1397 | module.exports = checkPropTypes;
1398 |
1399 | /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
1400 |
1401 | /***/ }),
1402 | /* 12 */
1403 | /***/ (function(module, exports, __webpack_require__) {
1404 |
1405 | "use strict";
1406 | /**
1407 | * Copyright (c) 2013-present, Facebook, Inc.
1408 | *
1409 | * This source code is licensed under the MIT license found in the
1410 | * LICENSE file in the root directory of this source tree.
1411 | */
1412 |
1413 |
1414 |
1415 | var emptyFunction = __webpack_require__(1);
1416 | var invariant = __webpack_require__(2);
1417 | var ReactPropTypesSecret = __webpack_require__(3);
1418 |
1419 | module.exports = function() {
1420 | function shim(props, propName, componentName, location, propFullName, secret) {
1421 | if (secret === ReactPropTypesSecret) {
1422 | // It is still safe when called from React.
1423 | return;
1424 | }
1425 | invariant(
1426 | false,
1427 | 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
1428 | 'Use PropTypes.checkPropTypes() to call them. ' +
1429 | 'Read more at http://fb.me/use-check-prop-types'
1430 | );
1431 | };
1432 | shim.isRequired = shim;
1433 | function getShim() {
1434 | return shim;
1435 | };
1436 | // Important!
1437 | // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
1438 | var ReactPropTypes = {
1439 | array: shim,
1440 | bool: shim,
1441 | func: shim,
1442 | number: shim,
1443 | object: shim,
1444 | string: shim,
1445 | symbol: shim,
1446 |
1447 | any: shim,
1448 | arrayOf: getShim,
1449 | element: shim,
1450 | instanceOf: getShim,
1451 | node: shim,
1452 | objectOf: getShim,
1453 | oneOf: getShim,
1454 | oneOfType: getShim,
1455 | shape: getShim,
1456 | exact: getShim
1457 | };
1458 |
1459 | ReactPropTypes.checkPropTypes = emptyFunction;
1460 | ReactPropTypes.PropTypes = ReactPropTypes;
1461 |
1462 | return ReactPropTypes;
1463 | };
1464 |
1465 |
1466 | /***/ }),
1467 | /* 13 */
1468 | /***/ (function(module, exports, __webpack_require__) {
1469 |
1470 | "use strict";
1471 |
1472 |
1473 | Object.defineProperty(exports, "__esModule", {
1474 | value: true
1475 | });
1476 | exports.swapArrayElements = swapArrayElements;
1477 | exports.isMouseBeyond = isMouseBeyond;
1478 | /*** Helper functions - they are decoupled because of testability */
1479 |
1480 | /**
1481 | * @param {array} items
1482 | * @param {number} indexFrom
1483 | * @param {number} indexTo
1484 | * @returns {array}
1485 | */
1486 | function swapArrayElements(items, indexFrom, indexTo) {
1487 | var item = items[indexTo];
1488 | items[indexTo] = items[indexFrom];
1489 | items[indexFrom] = item;
1490 | return items;
1491 | }
1492 |
1493 | /**
1494 | * @param {number} mousePos
1495 | * @param {number} elementPos
1496 | * @param {number} elementSize
1497 | * @returns {boolean}
1498 | */
1499 | function isMouseBeyond(mousePos, elementPos, elementSize, moveInMiddle) {
1500 | var breakPoint;
1501 | if (moveInMiddle) {
1502 | breakPoint = elementSize / 2; //break point is set to the middle line of element
1503 | } else {
1504 | breakPoint = 0;
1505 | }
1506 | var mouseOverlap = mousePos - elementPos;
1507 | return mouseOverlap > breakPoint;
1508 | }
1509 |
1510 | /***/ })
1511 | /******/ ]);
1512 | });
--------------------------------------------------------------------------------
/lib/standalone/react-sortable.min.js:
--------------------------------------------------------------------------------
1 | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("React")):"function"==typeof define&&define.amd?define(["React"],t):"object"==typeof exports?exports.Sortable=t(require("React")):e.Sortable=t(e.React)}("undefined"!=typeof self?self:this,function(e){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=0)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(1);Object.defineProperty(t,"sortable",{enumerable:!0,get:function(){return n.SortableComposition}}),Object.defineProperty(t,"Sortable",{enumerable:!0,get:function(){return n.SortableComposition}}),Object.defineProperty(t,"HORIZONTAL",{enumerable:!0,get:function(){return n.HORIZONTAL}}),Object.defineProperty(t,"VERTICAL",{enumerable:!0,get:function(){return n.VERTICAL}})},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b;return function(r){function n(){var e,r,o,u;i(this,n);for(var s=arguments.length,c=Array(s),f=0;fo}Object.defineProperty(t,"__esModule",{value:!0}),t.swapArrayElements=n,t.isMouseBeyond=o}])});
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-sortable",
3 | "version": "2.0.0",
4 | "description": "Make your React components sortable.",
5 | "main": "lib/index.js",
6 | "jsnext:main": "src/index.js",
7 | "scripts": {
8 | "build": "babel src --out-dir lib",
9 | "build:standalone": "webpack --config ./webpack.standalone.js",
10 | "preversion": "npm run build",
11 | "start": "npm run build -- --watch",
12 | "dev": "webpack-dev-server --config ./webpack.devConfig.js",
13 | "test": "jest --verbose",
14 | "selenium": "./node_modules/.bin/wdio ./webdriver/wdio-local.conf.js"
15 | },
16 | "repository": {
17 | "type": "git",
18 | "url": "https://github.com/danielstocks/react-sortable/"
19 | },
20 | "keywords": [
21 | "React",
22 | "sortable",
23 | "sorting",
24 | "drag",
25 | "drop",
26 | "dragndrop",
27 | "draganddrop"
28 | ],
29 | "author": "Daniel Stocks ",
30 | "license": "MIT",
31 | "dependencies": {
32 | "react": "16.x.x",
33 | "react-dom": "16.x.x"
34 | },
35 | "devDependencies": {
36 | "babel-cli": "6.26.x",
37 | "babel-core": "6.26.x",
38 | "babel-jest": "21.x.x",
39 | "babel-loader": "7.1.x",
40 | "babel-preset-es2015": "6.24.x",
41 | "babel-preset-react": "6.24.x",
42 | "babel-preset-stage-0": "6.24.x",
43 | "jest-cli": "21.x.x",
44 | "react": "16.x.x",
45 | "react-dom": "16.x.x",
46 | "react-redux": "5.0.6",
47 | "redux": "3.7.2",
48 | "wdio-jasmine-framework": "0.3.x",
49 | "webdriverio": "4.9.x",
50 | "webpack": "3.9.x",
51 | "webpack-dev-server": "2.9.x"
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/SortableComposition.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import PropTypes from 'prop-types'
3 | import { swapArrayElements, isMouseBeyond } from './helpers.js'
4 |
5 | export const VERTICAL = 'VERTICAL'
6 | export const HORIZONTAL = 'HORIZONTAL'
7 |
8 |
9 | /*** Higher-order component - this component works like a factory for draggable items */
10 |
11 | let draggingIndex = null
12 |
13 | export function SortableComposition(Component, flowDirection = VERTICAL) {
14 |
15 | return class Sortable extends React.Component {
16 |
17 | sortEnd = (e) => {
18 | e.preventDefault()
19 | draggingIndex = null
20 | }
21 |
22 | sortStart = (e) => {
23 | draggingIndex = e.currentTarget.dataset.id
24 | let dt = e.dataTransfer
25 | if (dt !== undefined) {
26 | e.dataTransfer.setData('text', e.target.innerHTML)
27 |
28 | //fix http://stackoverflow.com/questions/27656183/preserve-appearance-of-dragged-a-element-when-using-html5-draggable-attribute
29 | if (dt.setDragImage && e.currentTarget.tagName.toLowerCase() === 'a') {
30 | dt.setDragImage(e.target, 0, 0)
31 | }
32 | }
33 | }
34 |
35 | dragOver = (e) => {
36 | e.preventDefault();
37 | const { moveInMiddle, sortId } = this.props
38 | const overEl = e.currentTarget //underlying element
39 | const indexDragged = Number(overEl.dataset.id) //index of underlying element in the set DOM elements
40 | const indexFrom = Number(draggingIndex)
41 | const height = overEl.getBoundingClientRect().height
42 | const width = overEl.getBoundingClientRect().width
43 | const positionX = e.clientX
44 | const positionY = e.clientY
45 | const topOffset = overEl.getBoundingClientRect().top
46 | const leftOffset = overEl.getBoundingClientRect().left
47 | let mouseBeyond
48 | let { items } = this.props
49 |
50 |
51 | if (flowDirection === VERTICAL) {
52 | mouseBeyond = isMouseBeyond(positionY, topOffset, height, moveInMiddle)
53 | }
54 |
55 | if (flowDirection === HORIZONTAL) {
56 | mouseBeyond = isMouseBeyond(positionX, leftOffset, width, moveInMiddle)
57 | }
58 |
59 | let shouldSwapItems = isMouseBeyond && indexDragged !== indexFrom
60 |
61 | if (indexDragged !== indexFrom && mouseBeyond) {
62 | items = swapArrayElements(items, indexFrom, indexDragged)
63 | draggingIndex = indexDragged
64 | this.props.onSortItems(items)
65 | }
66 |
67 | }
68 |
69 | render() {
70 | let newProps = Object.assign({}, this.props)
71 | delete newProps.onSortItems
72 | const { sortId, ...props } = newProps
73 | return (
74 |
85 | )
86 | }
87 |
88 | }
89 |
90 | Sortable.propTypes = {
91 | items: PropTypes.array.isRequired,
92 | onSortItems: PropTypes.func.isRequired,
93 | sortId: PropTypes.number,
94 | };
95 |
96 | Sortable.defaultProps = {
97 | moveInMiddle: false
98 | };
99 |
100 | return Sortable
101 |
102 | }
103 |
--------------------------------------------------------------------------------
/src/helpers.js:
--------------------------------------------------------------------------------
1 | /*** Helper functions - they are decoupled because of testability */
2 |
3 |
4 | /**
5 | * @param {array} items
6 | * @param {number} indexFrom
7 | * @param {number} indexTo
8 | * @returns {array}
9 | */
10 | export function swapArrayElements(items, indexFrom, indexTo) {
11 | var item = items[indexTo]
12 | items[indexTo] = items[indexFrom]
13 | items[indexFrom] = item
14 | return items
15 | }
16 |
17 | /**
18 | * @param {number} mousePos
19 | * @param {number} elementPos
20 | * @param {number} elementSize
21 | * @returns {boolean}
22 | */
23 | export function isMouseBeyond(mousePos, elementPos, elementSize, moveInMiddle) {
24 | var breakPoint
25 | if (moveInMiddle) {
26 | breakPoint = elementSize / 2 //break point is set to the middle line of element
27 | } else {
28 | breakPoint = 0
29 | }
30 | var mouseOverlap = mousePos - elementPos
31 | return mouseOverlap > breakPoint
32 | }
33 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | export { SortableComposition as sortable } from './SortableComposition'
2 | export { SortableComposition as Sortable } from './SortableComposition'
3 | export { HORIZONTAL } from './SortableComposition'
4 | export { VERTICAL } from './SortableComposition'
5 |
6 |
--------------------------------------------------------------------------------
/webdriver/spec/drag&drop.js:
--------------------------------------------------------------------------------
1 |
2 | describe("drag&drop", function () {
3 | it("should ckeck drag & drop list", function () {
4 | browser.url("/");
5 | browser.pause(1000);
6 | browser.dragAndDrop("#list0", "#list1");
7 | browser.pause(1000);
8 | expect(browser.getText("#list0")).toContain("Crimson")
9 | })
10 | })
11 |
--------------------------------------------------------------------------------
/webdriver/wdio-local.conf.js:
--------------------------------------------------------------------------------
1 | exports.config = {
2 | specs: [
3 | "./webdriver/spec/drag&drop.js"
4 | ],
5 | capabilities: [{
6 | browserName: "chrome"
7 | }],
8 | logLevel: "silent",
9 | coloredLogs: true,
10 | screenshotPath: "./errorShots/",
11 | baseUrl: "http://localhost:8080/demo/",
12 | // Default timeout for all waitForXXX commands.
13 | waitforTimeout: 1000,
14 | framework: "jasmine",
15 | reporter: "spec",
16 | jasmineNodeOpts: {
17 | // Jasmine default timeout
18 | defaultTimeoutInterval: 180000
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | var path = require("path");
2 | var webpack = require("webpack");
3 |
4 | module.exports = {
5 | entry: "./examples/main.js",
6 | output: {
7 | path: __dirname,
8 | filename: "bundle.js"
9 | },
10 | devServer: {
11 | contentBase: './examples',
12 | host: '0.0.0.0'
13 | },
14 | devtool: 'source-map',
15 | module: {
16 | rules: [
17 | { test: /\.js?$/, use: 'babel-loader' },
18 | ]
19 | },
20 | watch: true
21 | };
22 |
--------------------------------------------------------------------------------
/webpack.devConfig.js:
--------------------------------------------------------------------------------
1 | var path = require("path");
2 | var webpack = require("webpack");
3 |
4 | module.exports = {
5 | entry: "./examples/basic-list/index.js",
6 | //entry: "./examples/basic-grid/index.js",
7 | //entry: "./examples/html-table/index.js",
8 | //entry: "./examples/redux/index.js",
9 | output: {
10 | path: __dirname,
11 | filename: "bundle.js"
12 | },
13 | devServer: {
14 | contentBase: './examples',
15 | contentBase: [path.join(__dirname, "examples"), path.join(__dirname, "css")]
16 | },
17 | devtool: 'source-map',
18 | module: {
19 | rules: [
20 | { test: /\.js?$/, use: 'babel-loader' },
21 | ]
22 | },
23 | watch: true
24 | };
25 |
--------------------------------------------------------------------------------
/webpack.standalone.js:
--------------------------------------------------------------------------------
1 | var path = require('path');
2 | const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
3 | var webpack = require('webpack');
4 |
5 | module.exports = [{
6 | entry: './src/index.js',
7 |
8 | output: {
9 | filename: './lib/standalone/react-sortable.js',
10 | libraryTarget: 'umd',
11 | library: 'Sortable'
12 | },
13 |
14 | module: {
15 | rules: [
16 | {
17 | test: /\.js$/,
18 | exclude: /(node_modules|bower_components)/,
19 | use: {
20 | loader: 'babel-loader'
21 | }
22 | }
23 | ]
24 | },
25 |
26 | externals: {
27 | react: 'React'
28 | }
29 | }, {
30 | entry: './src/index.js',
31 |
32 | output: {
33 | filename: './lib/standalone/react-sortable.min.js',
34 | libraryTarget: 'umd',
35 | library: 'Sortable'
36 | },
37 |
38 | module: {
39 | rules: [
40 | {
41 | test: /\.js$/,
42 | exclude: /(node_modules|bower_components)/,
43 | use: {
44 | loader: 'babel-loader'
45 | }
46 | }
47 | ]
48 | },
49 |
50 | externals: {
51 | react: 'React'
52 | },
53 |
54 | plugins: [
55 | new webpack.DefinePlugin({
56 | 'process.env': {
57 | NODE_ENV: JSON.stringify('production')
58 | }
59 | }),
60 | new UglifyJSPlugin()
61 | ]
62 | }];
63 |
--------------------------------------------------------------------------------