├── website
├── src
│ ├── styles
│ │ ├── font.scss
│ │ ├── custom-antd.scss
│ │ ├── space.scss
│ │ ├── globals.scss
│ │ ├── text.scss
│ │ ├── reset.scss
│ │ └── color.scss
│ ├── vite-env.d.ts
│ ├── main.tsx
│ └── App.tsx
├── README.md
├── .prettierignore
├── .eslintignore
├── tsconfig.node.json
├── .prettierrc
├── .eslintrc.json
├── .gitignore
├── .editorconfig
├── index.html
├── tsconfig.json
├── vite.config.ts
├── public
│ └── vite.svg
└── package.json
├── FUNDING.yml
├── pnpm-workspace.yaml
├── .vscode
└── settings.json
├── .prettierrc.js
├── src
├── SortableContainer
│ ├── defaultGetHelperDimensions.tsx
│ ├── defaultShouldCancelStart.tsx
│ ├── props.tsx
│ └── index.tsx
├── SortableHandle
│ └── index.tsx
├── Manager
│ └── index.tsx
├── AutoScroller
│ └── index.tsx
├── SortableElement
│ └── index.tsx
├── index.tsx
└── utils.tsx
├── tsconfig.json
├── .eslintrc.js
├── turbo.json
├── .gitignore
├── LICENSE.md
├── package.json
└── README.md
/website/src/styles/font.scss:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: hunghg255
2 |
--------------------------------------------------------------------------------
/website/src/styles/custom-antd.scss:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/pnpm-workspace.yaml:
--------------------------------------------------------------------------------
1 | packages:
2 | - 'website'
3 | - '.'
4 | - 'test'
5 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "typescript.tsdk": "node_modules/typescript/lib"
3 | }
4 |
--------------------------------------------------------------------------------
/website/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
= (props: P) => JSX.Element; 113 | 114 | export type WrappedComponent
= React.ComponentClass
| WrappedComponentFactory
;
115 |
--------------------------------------------------------------------------------
/website/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React, { Component, useState } from 'react';
2 | import { MenuOutlined } from '@ant-design/icons';
3 |
4 | import { Space, Table, Tag } from 'antd';
5 | import type { ColumnsType } from 'antd/es/table';
6 | import {
7 | arrayMove,
8 | SortableContainer,
9 | SortableContainerProps,
10 | SortableElement,
11 | SortableHandle,
12 | SortEnd,
13 | } from 'reactjs-table-dnd';
14 | import GitHubCorners from '@uiw/react-github-corners';
15 |
16 | interface DataType {
17 | key: string;
18 | name: string;
19 | age: number;
20 | address: string;
21 | tags: string[];
22 | index: number;
23 | }
24 |
25 | const columns: ColumnsType
2 |
3 |
7 | A Sort component for Reactjs and antd ✨.
8 |
85 | ));
86 | const SortableBody = SortableContainer((props: React.HTMLAttributes
95 | {items.map((value: any, index: any) => (
96 | //@ts-ignore
97 |
100 | );
101 | });
102 |
103 | class SortableComponent extends Component {
104 | state = {
105 | items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
106 | };
107 | onSortEnd = ({ oldIndex, newIndex }: any) => {
108 | this.setState(({ items }: any) => ({
109 | items: arrayMove(items, oldIndex, newIndex),
110 | }));
111 | };
112 | render() {
113 | //@ts-ignore
114 | return Ant Design Table
171 |
172 |
182 |
183 |
List Item
186 |
187 |
4 |
51 | {items.map((value, index) => (
52 |
55 | );
56 | });
57 |
58 | class SortableComponent extends Component {
59 | state = {
60 | items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
61 | };
62 | onSortEnd = ({ oldIndex, newIndex }) => {
63 | this.setState(({ items }) => ({
64 | items: arrayMove(items, oldIndex, newIndex),
65 | }));
66 | };
67 | render() {
68 | return
`lift: [32],`
`drop: [32],`
`cancel: [27],`
`up: [38, 37],`
`down: [40, 39]`
`}` | An object containing an array of keycodes for each keyboard-accessible action. |
93 | | pressDelay | Number | `0` | If you'd like elements to only become sortable after being pressed for a certain time, change this property. A good sensible default value for mobile is `200`. Cannot be used in conjunction with the `distance` prop. |
94 | | pressThreshold | Number | `5` | Number of pixels of movement to tolerate before ignoring a press event. |
95 | | distance | Number | `0` | If you'd like elements to only become sortable after being dragged a certain number of pixels. Cannot be used in conjunction with the `pressDelay` prop. |
96 | | shouldCancelStart | Function | [Function](https://github.com/clauderic/reactjs-table-dnd/blob/master/src/SortableContainer/index.js#L48) | This function is invoked before sorting begins, and can be used to programatically cancel sorting before it begins. By default, it will cancel sorting if the event target is either an `input`, `textarea`, `select`, `option`, or `button`. |
97 | | updateBeforeSortStart | Function | | This function is invoked before sorting begins. It can return a promise, allowing you to run asynchronous updates (such as `setState`) before sorting begins. `function({node, index, collection, isKeySorting}, event)` |
98 | | onSortStart | Function | | Callback that is invoked when sorting begins. `function({node, index, collection, isKeySorting}, event)` |
99 | | onSortMove | Function | | Callback that is invoked during sorting as the cursor moves. `function(event)` |
100 | | onSortOver | Function | | Callback that is invoked when moving over an item. `function({index, oldIndex, newIndex, collection, isKeySorting}, e)` |
101 | | onSortEnd | Function | | Callback that is invoked when sorting ends. `function({oldIndex, newIndex, collection, isKeySorting}, e)` |
102 | | useDragHandle | Boolean | `false` | If you're using the `SortableHandle` HOC, set this to `true` |
103 | | useWindowAsScrollContainer | Boolean | `false` | If you want, you can set the `window` as the scrolling container |
104 | | hideSortableGhost | Boolean | `true` | Whether to auto-hide the ghost element. By default, as a convenience, React Sortable List will automatically hide the element that is currently being sorted. Set this to false if you would like to apply your own styling. |
105 | | lockToContainerEdges | Boolean | `false` | You can lock movement of the sortable element to it's parent `SortableContainer` |
106 | | lockOffset | `OffsetValue`\* | [`OffsetValue`\*, `OffsetValue`\*] | `"50%"` | When`lockToContainerEdges`is set to`true`, this controls the offset distance between the sortable helper and the top/bottom edges of it's parent`SortableContainer`. Percentage values are relative to the height of the item currently being sorted. If you wish to specify different behaviours for locking to the _top_ of the container vs the _bottom_, you may also pass in an`array`(For example:`["0%", "100%"]`). |
107 | | getContainer | Function | | Optional function to return the scrollable container element. This property defaults to the `SortableContainer` element itself or (if `useWindowAsScrollContainer` is true) the window. Use this function to specify a custom container object (eg this is useful for integrating with certain 3rd party components such as `FlexTable`). This function is passed a single parameter (the `wrappedInstance` React element) and it is expected to return a DOM element. |
108 | | getHelperDimensions | Function | [Function](https://github.com/clauderic/reactjs-table-dnd/blob/master/src/SortableContainer/index.js#L74-L77) | Optional `function({node, index, collection})` that should return the computed dimensions of the SortableHelper. See [default implementation](https://github.com/clauderic/reactjs-table-dnd/blob/master/src/SortableContainer/defaultGetHelperDimensions.js) for more details |
109 | | helperContainer | HTMLElement | Function | `document.body` | By default, the cloned sortable helper is appended to the document body. Use this prop to specify a different container for the sortable clone to be appended to. Accepts an `HTMLElement` or a function returning an `HTMLElement` that will be invoked before right before sorting begins |
110 | | disableAutoscroll | Boolean | `false` | Disables autoscrolling while dragging |
111 |
112 | \* `OffsetValue` can either be a finite `Number` or a `String` made up of a number and a unit (`px` or `%`).
113 | Examples: `10` (which is the same as `"10px"`), `"50%"`
114 |
115 | #### SortableElement HOC
116 |
117 | | Property | Type | Default | Required? | Description |
118 | | :--------- | :--------------- | :------ | :-------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
119 | | index | Number | | ✓ | This is the element's sortableIndex within it's collection. This prop is required. |
120 | | collection | Number or String | `0` | | The collection the element is part of. This is useful if you have multiple groups of sortable elements within the same `SortableContainer`. [Example](http://clauderic.github.io/reactjs-table-dnd/#/basic-configuration/multiple-lists) |
121 | | disabled | Boolean | `false` | | Whether the element should be sortable or not |
122 |
123 | ### Accessibility
124 |
125 | React Sortable HOC supports keyboard sorting out of the box. To enable it, make sure your `SortableElement` or `SortableHandle` is focusable. This can be done by setting `tabIndex={0}` on the outermost HTML node rendered by the component you're enhancing with `SortableElement` or `SortableHandle`.
126 |
127 | Once an item is focused/tabbed to, pressing `SPACE` picks it up, `ArrowUp` or `ArrowLeft` moves it one place backward in the list, `ArrowDown` or `ArrowRight` moves items one place forward in the list, pressing `SPACE` again drops the item in its new position. Pressing `ESC` before the item is dropped will cancel the sort operations.
128 |
129 | ### Grid support
130 |
131 | Need to sort items in a grid? We've got you covered! Just set the `axis` prop to `xy`. Grid support is currently limited to a setup where all the cells in the grid have the same width and height, though we're working hard to get variable width support in the near future.
132 |
133 | ### Item disappearing when sorting / CSS issues
134 |
135 | Upon sorting, `reactjs-table-dnd` creates a clone of the element you are sorting (the _sortable-helper_) and appends it to the end of the `` tag. The original element will still be in-place to preserve its position in the DOM until the end of the drag (with inline-styling to make it invisible). If the _sortable-helper_ gets messed up from a CSS standpoint, consider that maybe your selectors to the draggable item are dependent on a parent element which isn't present anymore (again, since the _sortable-helper_ is at the end of the ``). This can also be a `z-index` issue, for example, when using `reactjs-table-dnd` within a Bootstrap modal, you'll need to increase the `z-index` of the SortableHelper so it is displayed on top of the modal
136 |
137 | ### Click events being swallowed
138 |
139 | By default, `reactjs-table-dnd` is triggered immediately on `mousedown`. If you'd like to prevent this behaviour, there are a number of strategies readily available. You can use the `distance` prop to set a minimum distance (in pixels) to be dragged before sorting is enabled. You can also use the `pressDelay` prop to add a delay before sorting is enabled. Alternatively
140 |
141 | ### Wrapper props not passed down to wrapped Component
142 |
143 | All props for `SortableContainer` and `SortableElement` listed above are intentionally consumed by the wrapper component and are **not** passed down to the wrapped component. To make them available pass down the desired prop again with a different name. E.g.:
144 |
145 | ```js
146 | const SortableItem = SortableElement(({ value, sortIndex }) => (
147 |
155 | {items.map((value, index) => (
156 |
159 | );
160 | });
161 | ```
162 |
163 | ### About
164 |
165 |
166 |
167 | Gia Hung – [hung.hg](https://hung.thedev.id)
168 |
--------------------------------------------------------------------------------
/src/SortableContainer/index.tsx:
--------------------------------------------------------------------------------
1 | //@ts-nocheck
2 | import * as React from 'react';
3 | import { findDOMNode } from 'react-dom';
4 | import invariant from 'invariant';
5 |
6 | import Manager from '../Manager';
7 | import { isSortableHandle } from '../SortableHandle';
8 |
9 | import {
10 | cloneNode,
11 | closest,
12 | events,
13 | getScrollingParent,
14 | getContainerGridGap,
15 | getEdgeOffset,
16 | getElementMargin,
17 | getLockPixelOffsets,
18 | getPosition,
19 | isTouchEvent,
20 | limit,
21 | NodeType,
22 | omit,
23 | provideDisplayName,
24 | setInlineStyles,
25 | setTransitionDuration,
26 | setTranslate3d,
27 | getTargetIndex,
28 | getScrollAdjustedBoundingClientRect,
29 | } from '../utils.js';
30 |
31 | import AutoScroller from '../AutoScroller';
32 | import { defaultProps, omittedProps, propTypes, validateProps, defaultKeyCodes } from './props';
33 |
34 | export const SortableContext = React.createContext({
35 | manager: {},
36 | });
37 |
38 | export default function sortableContainer(WrappedComponent, config = { withRef: false }) {
39 | return class WithSortableContainer extends React.Component {
40 | constructor(props) {
41 | super(props);
42 | const manager = new Manager();
43 |
44 | validateProps(props);
45 |
46 | this.manager = manager;
47 | this.wrappedInstance = React.createRef();
48 | this.sortableContextValue = { manager };
49 | this.events = {
50 | end: this.handleEnd,
51 | move: this.handleMove,
52 | start: this.handleStart,
53 | };
54 | }
55 |
56 | state = {};
57 |
58 | static displayName = provideDisplayName('sortableList', WrappedComponent);
59 | static defaultProps = defaultProps;
60 | static propTypes = propTypes;
61 |
62 | componentDidMount() {
63 | const { useWindowAsScrollContainer } = this.props;
64 | const container = this.getContainer();
65 |
66 | Promise.resolve(container).then(containerNode => {
67 | this.container = containerNode;
68 | this.document = this.container.ownerDocument || document;
69 |
70 | /*
71 | * Set our own default rather than using defaultProps because Jest
72 | * snapshots will serialize window, causing a RangeError
73 | */
74 | const contentWindow = this.props.contentWindow || this.document.defaultView || window;
75 |
76 | this.contentWindow = typeof contentWindow === 'function' ? contentWindow() : contentWindow;
77 |
78 | this.scrollContainer = useWindowAsScrollContainer
79 | ? this.document.scrollingElement || this.document.documentElement
80 | : getScrollingParent(this.container) || this.container;
81 |
82 | this.autoScroller = new AutoScroller(this.scrollContainer, this.onAutoScroll);
83 |
84 | Object.keys(this.events).forEach(key =>
85 | events[key].forEach(eventName => this.container.addEventListener(eventName, this.events[key], false)),
86 | );
87 |
88 | this.container.addEventListener('keydown', this.handleKeyDown);
89 | });
90 | }
91 |
92 | componentWillUnmount() {
93 | if (this.helper && this.helper.parentNode) {
94 | this.helper.parentNode.removeChild(this.helper);
95 | }
96 | if (!this.container) {
97 | return;
98 | }
99 |
100 | Object.keys(this.events).forEach(key =>
101 | events[key].forEach(eventName => this.container.removeEventListener(eventName, this.events[key])),
102 | );
103 | this.container.removeEventListener('keydown', this.handleKeyDown);
104 | }
105 |
106 | handleStart = event => {
107 | const { distance, shouldCancelStart } = this.props;
108 |
109 | if (event.button === 2 || shouldCancelStart(event)) {
110 | return;
111 | }
112 |
113 | this.touched = true;
114 | this.position = getPosition(event);
115 |
116 | const node = closest(event.target, el => el.sortableInfo != null);
117 |
118 | if (node && node.sortableInfo && this.nodeIsChild(node) && !this.state.sorting) {
119 | const { useDragHandle } = this.props;
120 | const { index, collection, disabled } = node.sortableInfo;
121 |
122 | if (disabled) {
123 | return;
124 | }
125 |
126 | if (useDragHandle && !closest(event.target, isSortableHandle)) {
127 | return;
128 | }
129 |
130 | this.manager.active = { collection, index };
131 |
132 | /*
133 | * Fixes a bug in Firefox where the :active state of anchor tags
134 | * prevent subsequent 'mousemove' events from being fired
135 | */
136 | if (!isTouchEvent(event) && event.target.tagName === NodeType.Anchor) {
137 | event.preventDefault();
138 | }
139 |
140 | if (!distance) {
141 | if (this.props.pressDelay === 0) {
142 | this.handlePress(event);
143 | } else {
144 | this.pressTimer = setTimeout(() => this.handlePress(event), this.props.pressDelay);
145 | }
146 | }
147 | }
148 | };
149 |
150 | nodeIsChild = node => {
151 | return node.sortableInfo.manager === this.manager;
152 | };
153 |
154 | handleMove = event => {
155 | const { distance, pressThreshold } = this.props;
156 |
157 | if (!this.state.sorting && this.touched && !this._awaitingUpdateBeforeSortStart) {
158 | const position = getPosition(event);
159 | const delta = {
160 | x: this.position.x - position.x,
161 | y: this.position.y - position.y,
162 | };
163 | const combinedDelta = Math.abs(delta.x) + Math.abs(delta.y);
164 |
165 | this.delta = delta;
166 |
167 | if (!distance && (!pressThreshold || combinedDelta >= pressThreshold)) {
168 | clearTimeout(this.cancelTimer);
169 | this.cancelTimer = setTimeout(this.cancel, 0);
170 | } else if (distance && combinedDelta >= distance && this.manager.isActive()) {
171 | this.handlePress(event);
172 | }
173 | }
174 | };
175 |
176 | handleEnd = () => {
177 | this.touched = false;
178 | this.cancel();
179 | };
180 |
181 | cancel = () => {
182 | const { distance } = this.props;
183 | const { sorting } = this.state;
184 |
185 | if (!sorting) {
186 | if (!distance) {
187 | clearTimeout(this.pressTimer);
188 | }
189 | this.manager.active = null;
190 | }
191 | };
192 |
193 | handlePress = async event => {
194 | const active = this.manager.getActive();
195 |
196 | if (active) {
197 | const {
198 | axis,
199 | getHelperDimensions,
200 | helperClass,
201 | hideSortableGhost,
202 | updateBeforeSortStart,
203 | onSortStart,
204 | useWindowAsScrollContainer,
205 | } = this.props;
206 | const { node, collection } = active;
207 | const { isKeySorting } = this.manager;
208 |
209 | if (typeof updateBeforeSortStart === 'function') {
210 | this._awaitingUpdateBeforeSortStart = true;
211 |
212 | try {
213 | const { index } = node.sortableInfo;
214 | await updateBeforeSortStart({ collection, index, node, isKeySorting }, event);
215 | } finally {
216 | this._awaitingUpdateBeforeSortStart = false;
217 | }
218 | }
219 |
220 | // Need to get the latest value for `index` in case it changes during `updateBeforeSortStart`
221 | const { index } = node.sortableInfo;
222 | const margin = getElementMargin(node);
223 | const gridGap = getContainerGridGap(this.container);
224 | const containerBoundingRect = this.scrollContainer.getBoundingClientRect();
225 | const dimensions = getHelperDimensions({ index, node, collection });
226 |
227 | this.node = node;
228 | this.margin = margin;
229 | this.gridGap = gridGap;
230 | this.width = dimensions.width;
231 | this.height = dimensions.height;
232 | this.marginOffset = {
233 | x: this.margin.left + this.margin.right + this.gridGap.x,
234 | y: Math.max(this.margin.top, this.margin.bottom, this.gridGap.y),
235 | };
236 | this.boundingClientRect = node.getBoundingClientRect();
237 | this.containerBoundingRect = containerBoundingRect;
238 | this.index = index;
239 | this.newIndex = index;
240 |
241 | this.axis = {
242 | x: axis.indexOf('x') >= 0,
243 | y: axis.indexOf('y') >= 0,
244 | };
245 | this.offsetEdge = getEdgeOffset(node, this.container);
246 |
247 | if (isKeySorting) {
248 | this.initialOffset = getPosition({
249 | ...event,
250 | pageX: this.boundingClientRect.left,
251 | pageY: this.boundingClientRect.top,
252 | });
253 | } else {
254 | this.initialOffset = getPosition(event);
255 | }
256 |
257 | this.initialScroll = {
258 | left: this.scrollContainer.scrollLeft,
259 | top: this.scrollContainer.scrollTop,
260 | };
261 |
262 | this.initialWindowScroll = {
263 | left: window.pageXOffset,
264 | top: window.pageYOffset,
265 | };
266 |
267 | this.helper = this.helperContainer.appendChild(cloneNode(node));
268 |
269 | setInlineStyles(this.helper, {
270 | boxSizing: 'border-box',
271 | height: `${this.height}px`,
272 | left: `${this.boundingClientRect.left - margin.left}px`,
273 | pointerEvents: 'none',
274 | position: 'fixed',
275 | top: `${this.boundingClientRect.top - margin.top}px`,
276 | width: `${this.width}px`,
277 | });
278 |
279 | if (isKeySorting) {
280 | this.helper.focus();
281 | }
282 |
283 | if (hideSortableGhost) {
284 | this.sortableGhost = node;
285 |
286 | setInlineStyles(node, {
287 | opacity: 0,
288 | visibility: 'hidden',
289 | });
290 | }
291 |
292 | this.minTranslate = {};
293 | this.maxTranslate = {};
294 |
295 | if (isKeySorting) {
296 | const {
297 | top: containerTop,
298 | left: containerLeft,
299 | width: containerWidth,
300 | height: containerHeight,
301 | } = useWindowAsScrollContainer
302 | ? {
303 | top: 0,
304 | left: 0,
305 | width: this.contentWindow.innerWidth,
306 | height: this.contentWindow.innerHeight,
307 | }
308 | : this.containerBoundingRect;
309 | const containerBottom = containerTop + containerHeight;
310 | const containerRight = containerLeft + containerWidth;
311 |
312 | if (this.axis.x) {
313 | this.minTranslate.x = containerLeft - this.boundingClientRect.left;
314 | this.maxTranslate.x = containerRight - (this.boundingClientRect.left + this.width);
315 | }
316 |
317 | if (this.axis.y) {
318 | this.minTranslate.y = containerTop - this.boundingClientRect.top;
319 | this.maxTranslate.y = containerBottom - (this.boundingClientRect.top + this.height);
320 | }
321 | } else {
322 | if (this.axis.x) {
323 | this.minTranslate.x =
324 | (useWindowAsScrollContainer ? 0 : containerBoundingRect.left) -
325 | this.boundingClientRect.left -
326 | this.width / 2;
327 | this.maxTranslate.x =
328 | (useWindowAsScrollContainer
329 | ? this.contentWindow.innerWidth
330 | : containerBoundingRect.left + containerBoundingRect.width) -
331 | this.boundingClientRect.left -
332 | this.width / 2;
333 | }
334 |
335 | if (this.axis.y) {
336 | this.minTranslate.y =
337 | (useWindowAsScrollContainer ? 0 : containerBoundingRect.top) -
338 | this.boundingClientRect.top -
339 | this.height / 2;
340 | this.maxTranslate.y =
341 | (useWindowAsScrollContainer
342 | ? this.contentWindow.innerHeight
343 | : containerBoundingRect.top + containerBoundingRect.height) -
344 | this.boundingClientRect.top -
345 | this.height / 2;
346 | }
347 | }
348 |
349 | if (helperClass) {
350 | helperClass.split(' ').forEach(className => this.helper.classList.add(className));
351 | }
352 |
353 | this.listenerNode = event.touches ? event.target : this.contentWindow;
354 |
355 | if (isKeySorting) {
356 | this.listenerNode.addEventListener('wheel', this.handleKeyEnd, true);
357 | this.listenerNode.addEventListener('mousedown', this.handleKeyEnd, true);
358 | this.listenerNode.addEventListener('keydown', this.handleKeyDown);
359 | } else {
360 | events.move.forEach(eventName => this.listenerNode.addEventListener(eventName, this.handleSortMove, false));
361 | events.end.forEach(eventName => this.listenerNode.addEventListener(eventName, this.handleSortEnd, false));
362 | }
363 |
364 | this.setState({
365 | sorting: true,
366 | sortingIndex: index,
367 | });
368 |
369 | if (onSortStart) {
370 | onSortStart(
371 | {
372 | node,
373 | index,
374 | collection,
375 | isKeySorting,
376 | nodes: this.manager.getOrderedRefs(),
377 | helper: this.helper,
378 | },
379 | event,
380 | );
381 | }
382 |
383 | if (isKeySorting) {
384 | // Readjust positioning in case re-rendering occurs onSortStart
385 | this.keyMove(0);
386 | }
387 | }
388 | };
389 |
390 | handleSortMove = event => {
391 | const { onSortMove } = this.props;
392 |
393 | // Prevent scrolling on mobile
394 | if (typeof event.preventDefault === 'function' && event.cancelable) {
395 | event.preventDefault();
396 | }
397 |
398 | this.updateHelperPosition(event);
399 | this.animateNodes();
400 | this.autoscroll();
401 |
402 | if (onSortMove) {
403 | onSortMove(event);
404 | }
405 | };
406 |
407 | handleSortEnd = event => {
408 | const { hideSortableGhost, onSortEnd } = this.props;
409 | const {
410 | active: { collection },
411 | isKeySorting,
412 | } = this.manager;
413 | const nodes = this.manager.getOrderedRefs();
414 |
415 | // Remove the event listeners if the node is still in the DOM
416 | if (this.listenerNode) {
417 | if (isKeySorting) {
418 | this.listenerNode.removeEventListener('wheel', this.handleKeyEnd, true);
419 | this.listenerNode.removeEventListener('mousedown', this.handleKeyEnd, true);
420 | this.listenerNode.removeEventListener('keydown', this.handleKeyDown);
421 | } else {
422 | events.move.forEach(eventName => this.listenerNode.removeEventListener(eventName, this.handleSortMove));
423 | events.end.forEach(eventName => this.listenerNode.removeEventListener(eventName, this.handleSortEnd));
424 | }
425 | }
426 |
427 | // Remove the helper from the DOM
428 | this.helper.parentNode.removeChild(this.helper);
429 |
430 | if (hideSortableGhost && this.sortableGhost) {
431 | setInlineStyles(this.sortableGhost, {
432 | opacity: '',
433 | visibility: '',
434 | });
435 | }
436 |
437 | for (let i = 0, len = nodes.length; i < len; i++) {
438 | const node = nodes[i];
439 | const el = node.node;
440 |
441 | // Clear the cached offset/boundingClientRect
442 | node.edgeOffset = null;
443 | node.boundingClientRect = null;
444 |
445 | // Remove the transforms / transitions
446 | setTranslate3d(el, null);
447 | setTransitionDuration(el, null);
448 | node.translate = null;
449 | }
450 |
451 | // Stop autoscroll
452 | this.autoScroller.clear();
453 |
454 | // Update manager state
455 | this.manager.active = null;
456 | this.manager.isKeySorting = false;
457 |
458 | this.setState({
459 | sorting: false,
460 | sortingIndex: null,
461 | });
462 |
463 | if (typeof onSortEnd === 'function') {
464 | onSortEnd(
465 | {
466 | collection,
467 | newIndex: this.newIndex,
468 | oldIndex: this.index,
469 | isKeySorting,
470 | nodes,
471 | },
472 | event,
473 | );
474 | }
475 |
476 | this.touched = false;
477 | };
478 |
479 | updateHelperPosition(event) {
480 | const {
481 | lockAxis,
482 | lockOffset,
483 | lockToContainerEdges,
484 | transitionDuration,
485 | keyboardSortingTransitionDuration = transitionDuration,
486 | } = this.props;
487 | const { isKeySorting } = this.manager;
488 | const { ignoreTransition } = event;
489 |
490 | const offset = getPosition(event);
491 | const translate = {
492 | x: offset.x - this.initialOffset.x,
493 | y: offset.y - this.initialOffset.y,
494 | };
495 |
496 | // Adjust for window scroll
497 | translate.y -= window.pageYOffset - this.initialWindowScroll.top;
498 | translate.x -= window.pageXOffset - this.initialWindowScroll.left;
499 |
500 | this.translate = translate;
501 |
502 | if (lockToContainerEdges) {
503 | const [minLockOffset, maxLockOffset] = getLockPixelOffsets({
504 | height: this.height,
505 | lockOffset,
506 | width: this.width,
507 | });
508 | const minOffset = {
509 | x: this.width / 2 - minLockOffset.x,
510 | y: this.height / 2 - minLockOffset.y,
511 | };
512 | const maxOffset = {
513 | x: this.width / 2 - maxLockOffset.x,
514 | y: this.height / 2 - maxLockOffset.y,
515 | };
516 |
517 | translate.x = limit(this.minTranslate.x + minOffset.x, this.maxTranslate.x - maxOffset.x, translate.x);
518 | translate.y = limit(this.minTranslate.y + minOffset.y, this.maxTranslate.y - maxOffset.y, translate.y);
519 | }
520 |
521 | if (lockAxis === 'x') {
522 | translate.y = 0;
523 | } else if (lockAxis === 'y') {
524 | translate.x = 0;
525 | }
526 |
527 | if (isKeySorting && keyboardSortingTransitionDuration && !ignoreTransition) {
528 | setTransitionDuration(this.helper, keyboardSortingTransitionDuration);
529 | }
530 |
531 | setTranslate3d(this.helper, translate);
532 | }
533 |
534 | animateNodes() {
535 | const { transitionDuration, hideSortableGhost, onSortOver } = this.props;
536 | const { containerScrollDelta, windowScrollDelta } = this;
537 | const nodes = this.manager.getOrderedRefs();
538 | const sortingOffset = {
539 | left: this.offsetEdge.left + this.translate.x + containerScrollDelta.left,
540 | top: this.offsetEdge.top + this.translate.y + containerScrollDelta.top,
541 | };
542 | const { isKeySorting } = this.manager;
543 |
544 | const prevIndex = this.newIndex;
545 | this.newIndex = null;
546 |
547 | for (let i = 0, len = nodes.length; i < len; i++) {
548 | const { node } = nodes[i];
549 | const { index } = node.sortableInfo;
550 | const width = node.offsetWidth;
551 | const height = node.offsetHeight;
552 | const offset = {
553 | height: this.height > height ? height / 2 : this.height / 2,
554 | width: this.width > width ? width / 2 : this.width / 2,
555 | };
556 |
557 | // For keyboard sorting, we want user input to dictate the position of the nodes
558 | const mustShiftBackward = isKeySorting && index > this.index && index <= prevIndex;
559 | const mustShiftForward = isKeySorting && index < this.index && index >= prevIndex;
560 |
561 | const translate = {
562 | x: 0,
563 | y: 0,
564 | };
565 | let { edgeOffset } = nodes[i];
566 |
567 | // If we haven't cached the node's offsetTop / offsetLeft value
568 | if (!edgeOffset) {
569 | edgeOffset = getEdgeOffset(node, this.container);
570 | nodes[i].edgeOffset = edgeOffset;
571 | // While we're at it, cache the boundingClientRect, used during keyboard sorting
572 | if (isKeySorting) {
573 | nodes[i].boundingClientRect = getScrollAdjustedBoundingClientRect(node, containerScrollDelta);
574 | }
575 | }
576 |
577 | // Get a reference to the next and previous node
578 | const nextNode = i < nodes.length - 1 && nodes[i + 1];
579 | const prevNode = i > 0 && nodes[i - 1];
580 |
581 | // Also cache the next node's edge offset if needed.
582 | // We need this for calculating the animation in a grid setup
583 | if (nextNode && !nextNode.edgeOffset) {
584 | nextNode.edgeOffset = getEdgeOffset(nextNode.node, this.container);
585 | if (isKeySorting) {
586 | nextNode.boundingClientRect = getScrollAdjustedBoundingClientRect(nextNode.node, containerScrollDelta);
587 | }
588 | }
589 |
590 | // If the node is the one we're currently animating, skip it
591 | if (index === this.index) {
592 | if (hideSortableGhost) {
593 | /*
594 | * With windowing libraries such as `react-virtualized`, the sortableGhost
595 | * node may change while scrolling down and then back up (or vice-versa),
596 | * so we need to update the reference to the new node just to be safe.
597 | */
598 | this.sortableGhost = node;
599 |
600 | setInlineStyles(node, {
601 | opacity: 0,
602 | visibility: 'hidden',
603 | });
604 | }
605 | continue;
606 | }
607 |
608 | if (transitionDuration) {
609 | setTransitionDuration(node, transitionDuration);
610 | }
611 |
612 | if (this.axis.x) {
613 | if (this.axis.y) {
614 | // Calculations for a grid setup
615 | if (
616 | mustShiftForward ||
617 | (index < this.index &&
618 | ((sortingOffset.left + windowScrollDelta.left - offset.width <= edgeOffset.left &&
619 | sortingOffset.top + windowScrollDelta.top <= edgeOffset.top + offset.height) ||
620 | sortingOffset.top + windowScrollDelta.top + offset.height <= edgeOffset.top))
621 | ) {
622 | // If the current node is to the left on the same row, or above the node that's being dragged
623 | // then move it to the right
624 | translate.x = this.width + this.marginOffset.x;
625 | if (edgeOffset.left + translate.x > this.containerBoundingRect.width - offset.width * 2) {
626 | // If it moves passed the right bounds, then animate it to the first position of the next row.
627 | // We just use the offset of the next node to calculate where to move, because that node's original position
628 | // is exactly where we want to go
629 | if (nextNode) {
630 | translate.x = nextNode.edgeOffset.left - edgeOffset.left;
631 | translate.y = nextNode.edgeOffset.top - edgeOffset.top;
632 | }
633 | }
634 | if (this.newIndex === null) {
635 | this.newIndex = index;
636 | }
637 | } else if (
638 | mustShiftBackward ||
639 | (index > this.index &&
640 | ((sortingOffset.left + windowScrollDelta.left + offset.width >= edgeOffset.left &&
641 | sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top) ||
642 | sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top + height))
643 | ) {
644 | // If the current node is to the right on the same row, or below the node that's being dragged
645 | // then move it to the left
646 | translate.x = -(this.width + this.marginOffset.x);
647 | if (edgeOffset.left + translate.x < this.containerBoundingRect.left + offset.width) {
648 | // If it moves passed the left bounds, then animate it to the last position of the previous row.
649 | // We just use the offset of the previous node to calculate where to move, because that node's original position
650 | // is exactly where we want to go
651 | if (prevNode) {
652 | translate.x = prevNode.edgeOffset.left - edgeOffset.left;
653 | translate.y = prevNode.edgeOffset.top - edgeOffset.top;
654 | }
655 | }
656 | this.newIndex = index;
657 | }
658 | } else {
659 | if (
660 | mustShiftBackward ||
661 | (index > this.index && sortingOffset.left + windowScrollDelta.left + offset.width >= edgeOffset.left)
662 | ) {
663 | translate.x = -(this.width + this.marginOffset.x);
664 | this.newIndex = index;
665 | } else if (
666 | mustShiftForward ||
667 | (index < this.index && sortingOffset.left + windowScrollDelta.left <= edgeOffset.left + offset.width)
668 | ) {
669 | translate.x = this.width + this.marginOffset.x;
670 |
671 | if (this.newIndex == null) {
672 | this.newIndex = index;
673 | }
674 | }
675 | }
676 | } else if (this.axis.y) {
677 | if (
678 | mustShiftBackward ||
679 | (index > this.index && sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top)
680 | ) {
681 | translate.y = -(this.height + this.marginOffset.y);
682 | this.newIndex = index;
683 | } else if (
684 | mustShiftForward ||
685 | (index < this.index && sortingOffset.top + windowScrollDelta.top <= edgeOffset.top + offset.height)
686 | ) {
687 | translate.y = this.height + this.marginOffset.y;
688 | if (this.newIndex == null) {
689 | this.newIndex = index;
690 | }
691 | }
692 | }
693 |
694 | setTranslate3d(node, translate);
695 | nodes[i].translate = translate;
696 | }
697 |
698 | if (this.newIndex == null) {
699 | this.newIndex = this.index;
700 | }
701 |
702 | if (isKeySorting) {
703 | // If keyboard sorting, we want the user input to dictate index, not location of the helper
704 | this.newIndex = prevIndex;
705 | }
706 |
707 | const oldIndex = isKeySorting ? this.prevIndex : prevIndex;
708 | if (onSortOver && this.newIndex !== oldIndex) {
709 | onSortOver({
710 | collection: this.manager.active.collection,
711 | index: this.index,
712 | newIndex: this.newIndex,
713 | oldIndex,
714 | isKeySorting,
715 | nodes,
716 | helper: this.helper,
717 | });
718 | }
719 | }
720 |
721 | autoscroll = () => {
722 | const { disableAutoscroll } = this.props;
723 | const { isKeySorting } = this.manager;
724 |
725 | if (disableAutoscroll) {
726 | this.autoScroller.clear();
727 | return;
728 | }
729 |
730 | if (isKeySorting) {
731 | const translate = { ...this.translate };
732 | let scrollX = 0;
733 | let scrollY = 0;
734 |
735 | if (this.axis.x) {
736 | translate.x = Math.min(this.maxTranslate.x, Math.max(this.minTranslate.x, this.translate.x));
737 | scrollX = this.translate.x - translate.x;
738 | }
739 |
740 | if (this.axis.y) {
741 | translate.y = Math.min(this.maxTranslate.y, Math.max(this.minTranslate.y, this.translate.y));
742 | scrollY = this.translate.y - translate.y;
743 | }
744 |
745 | this.translate = translate;
746 | setTranslate3d(this.helper, this.translate);
747 | this.scrollContainer.scrollLeft += scrollX;
748 | this.scrollContainer.scrollTop += scrollY;
749 |
750 | return;
751 | }
752 |
753 | this.autoScroller.update({
754 | height: this.height,
755 | maxTranslate: this.maxTranslate,
756 | minTranslate: this.minTranslate,
757 | translate: this.translate,
758 | width: this.width,
759 | });
760 | };
761 |
762 | onAutoScroll = offset => {
763 | this.translate.x += offset.left;
764 | this.translate.y += offset.top;
765 |
766 | this.animateNodes();
767 | };
768 |
769 | getWrappedInstance() {
770 | invariant(
771 | config.withRef,
772 | 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call',
773 | );
774 |
775 | return this.wrappedInstance.current;
776 | }
777 |
778 | getContainer() {
779 | const { getContainer } = this.props;
780 |
781 | if (typeof getContainer !== 'function') {
782 | return findDOMNode(this);
783 | }
784 |
785 | return getContainer(config.withRef ? this.getWrappedInstance() : undefined);
786 | }
787 |
788 | handleKeyDown = event => {
789 | const { keyCode } = event;
790 | const { shouldCancelStart, keyCodes: customKeyCodes = {} } = this.props;
791 |
792 | const keyCodes = {
793 | ...defaultKeyCodes,
794 | ...customKeyCodes,
795 | };
796 |
797 | if (
798 | (this.manager.active && !this.manager.isKeySorting) ||
799 | (!this.manager.active &&
800 | (!keyCodes.lift.includes(keyCode) || shouldCancelStart(event) || !this.isValidSortingTarget(event)))
801 | ) {
802 | return;
803 | }
804 |
805 | event.stopPropagation();
806 | event.preventDefault();
807 |
808 | if (keyCodes.lift.includes(keyCode) && !this.manager.active) {
809 | this.keyLift(event);
810 | } else if (keyCodes.drop.includes(keyCode) && this.manager.active) {
811 | this.keyDrop(event);
812 | } else if (keyCodes.cancel.includes(keyCode)) {
813 | this.newIndex = this.manager.active.index;
814 | this.keyDrop(event);
815 | } else if (keyCodes.up.includes(keyCode)) {
816 | this.keyMove(-1);
817 | } else if (keyCodes.down.includes(keyCode)) {
818 | this.keyMove(1);
819 | }
820 | };
821 |
822 | keyLift = event => {
823 | const { target } = event;
824 | const node = closest(target, el => el.sortableInfo != null);
825 | const { index, collection } = node.sortableInfo;
826 |
827 | this.initialFocusedNode = target;
828 |
829 | this.manager.isKeySorting = true;
830 | this.manager.active = {
831 | index,
832 | collection,
833 | };
834 |
835 | this.handlePress(event);
836 | };
837 |
838 | keyMove = shift => {
839 | const nodes = this.manager.getOrderedRefs();
840 | const { index: lastIndex } = nodes[nodes.length - 1].node.sortableInfo;
841 | const newIndex = this.newIndex + shift;
842 | const prevIndex = this.newIndex;
843 |
844 | if (newIndex < 0 || newIndex > lastIndex) {
845 | return;
846 | }
847 |
848 | this.prevIndex = prevIndex;
849 | this.newIndex = newIndex;
850 |
851 | const targetIndex = getTargetIndex(this.newIndex, this.prevIndex, this.index);
852 | const target = nodes.find(({ node }) => node.sortableInfo.index === targetIndex);
853 | const { node: targetNode } = target;
854 |
855 | const scrollDelta = this.containerScrollDelta;
856 | const targetBoundingClientRect =
857 | target.boundingClientRect || getScrollAdjustedBoundingClientRect(targetNode, scrollDelta);
858 | const targetTranslate = target.translate || { x: 0, y: 0 };
859 |
860 | const targetPosition = {
861 | top: targetBoundingClientRect.top + targetTranslate.y - scrollDelta.top,
862 | left: targetBoundingClientRect.left + targetTranslate.x - scrollDelta.left,
863 | };
864 |
865 | const shouldAdjustForSize = prevIndex < newIndex;
866 | const sizeAdjustment = {
867 | x: shouldAdjustForSize && this.axis.x ? targetNode.offsetWidth - this.width : 0,
868 | y: shouldAdjustForSize && this.axis.y ? targetNode.offsetHeight - this.height : 0,
869 | };
870 |
871 | this.handleSortMove({
872 | pageX: targetPosition.left + sizeAdjustment.x,
873 | pageY: targetPosition.top + sizeAdjustment.y,
874 | ignoreTransition: shift === 0,
875 | });
876 | };
877 |
878 | keyDrop = event => {
879 | this.handleSortEnd(event);
880 |
881 | if (this.initialFocusedNode) {
882 | this.initialFocusedNode.focus();
883 | }
884 | };
885 |
886 | handleKeyEnd = event => {
887 | if (this.manager.active) {
888 | this.keyDrop(event);
889 | }
890 | };
891 |
892 | isValidSortingTarget = event => {
893 | const { useDragHandle } = this.props;
894 | const { target } = event;
895 | const node = closest(target, el => el.sortableInfo != null);
896 |
897 | return (
898 | node &&
899 | node.sortableInfo &&
900 | !node.sortableInfo.disabled &&
901 | (useDragHandle ? isSortableHandle(target) : target.sortableInfo)
902 | );
903 | };
904 |
905 | render() {
906 | const ref = config.withRef ? this.wrappedInstance : null;
907 |
908 | return (
909 |