Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removable items by moving them out of bounds #16

Merged
merged 3 commits into from
Jul 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .storybook/example.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Table from '../examples/Table';
import TableAuto from '../examples/TableAuto';
import SuperSimple from '../examples/SuperSimple';
import Removable from '../examples/Removable';
import RemovableByMove from '../examples/RemovableByMove';
import Handle from '../examples/Handle';
import Disabled from '../examples/Disabled';
import NoAnimations from '../examples/NoAnimations';
Expand All @@ -15,10 +16,11 @@ import ScrollingContainer from '../examples/ScrollingContainer';

storiesOf('List', module)
.add('Basic', () => <Basic />)
.add('Table Fixed Cell Widths', () => <Table />)
.add('Table Auto Cell Widths', () => <TableAuto />)
.add('Table fixed cell widths', () => <Table />)
.add('Table auto cell widths', () => <TableAuto />)
.add('Super simple', () => <SuperSimple />)
.add('Removable', () => <Removable />)
.add('Removable by move', () => <RemovableByMove />)
.add('Handle', () => <Handle />)
.add('Disabled', () => <Disabled />)
.add('No animations', () => <NoAnimations />)
Expand Down
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ renderItem: (params: {
index?: number;
isDragged: boolean;
isSelected: boolean;
isOutOfBounds: boolean;
props: {
key?: number;
tabIndex?: number;
Expand All @@ -117,6 +118,7 @@ renderItem: (params: {
- `index` - the item index (order)
- `isDragged` - `true` if the item is dragged, great for styling purposes
- `isSelected` - `true` if the item is lifted with the `space`
- `isOutOfBounds` - `true` if the item is dragged far left or right
- `props` - it has multiple props that you need to spread over your item element

### values
Expand All @@ -130,13 +132,14 @@ An array of values. The value can be a string or any more complex object. The le
### onChange

```ts
onChange: (meta: { oldIndex: number; newIndex: number }) => void
onChange: (meta: { oldIndex: number; newIndex: number, targetRect: ClientRect }) => void
```

Called when the item is dropped to a new location:

- `oldIndex` - the initial position of the element (0 indexed)
- `newIndex` - the new position of the element (0 indexed)
- `newIndex` - the new position of the element (0 indexed), -1 when `removableByMove` is set and item dropped out of bounds
- `targetRect` - [getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of dropped item

The List component is `stateless` and `controlled` so you need to implement this function to change the order of input `values`. Check the initial example.

Expand All @@ -148,6 +151,14 @@ beforeDrag?: (params: { elements: Element[]; index: number }) => void;

Called when a valid drag is initiated. It provides a direct access to all list DOM elements and the index of dragged item. This can be useful when you need to do some upfront measurements like when building a [table with variable column widths](https://react-movable.netlify.com/?selectedKind=List&selectedStory=Table%20Auto%20Cell%20Widths).

### removableByMove

```ts
removableByMove: boolean;
```

Default is `false`. When set to `true` and an item is dragged far left or far right (out of bounds), the original gap disappears (animated) and following item drop will cause `onChange` being called with `newIndex = -1`. You can use that to remove the item from your `values` state. [Example](https://react-movable.netlify.com/?selectedKind=List&selectedStory=Removable%20by%20move).

### transitionDuration

```ts
Expand Down
37 changes: 37 additions & 0 deletions e2e/removable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import {
Examples,
getTestUrl,
trackMouse,
untrackMouse,
addFontStyles,
getListItems
} from './utils';

jest.setTimeout(10000);

beforeEach(async () => {
await page.goto(getTestUrl(Examples.REMOVABLE));
await page.setViewport({ width: 1030, height: 800 });
await addFontStyles(page);
});

test('dnd the second item out the bounds to be removed', async () => {
await trackMouse(page);
await page.mouse.move(517, 275);
await page.mouse.down();
await page.mouse.move(828, 222);
await page.mouse.up();
// make sure that originally dragged item is visible (rendered)
// in a new place
await page.waitForSelector(`#root li:nth-child(1)`, {
visible: true
});
expect(await getListItems(page)).toEqual([
'You can remove items by moving them far left or right. Also, onChange always gives you the getBoundingClientRect of the dropped item.',
'Item 3',
'Item 4',
'Item 5',
'Item 6'
]);
await untrackMouse(page);
});
5 changes: 4 additions & 1 deletion e2e/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ export enum Examples {
BASIC,
HEIGHTS,
SCROLLING_CONTAINER,
SCROLLING_WINDOW
SCROLLING_WINDOW,
REMOVABLE
}

export const getTestUrl = (example: Examples): string => {
Expand All @@ -18,6 +19,8 @@ export const getTestUrl = (example: Examples): string => {
return `http://localhost:${PORT}/iframe.html?selectedKind=List&selectedStory=Scrolling%20container`;
case Examples.SCROLLING_WINDOW:
return `http://localhost:${PORT}/iframe.html?selectedKind=List&selectedStory=Scrolling%20window`;
case Examples.REMOVABLE:
return `http://localhost:${PORT}/iframe.html?selectedKind=List&selectedStory=Removable%20by%20move`;
}
};

Expand Down
90 changes: 90 additions & 0 deletions examples/RemovableByMove.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import * as React from 'react';
import { List, arrayMove, arrayRemove } from '../src/index';

const initialState = {
items: [
'You can remove items by moving them far left or right. Also, onChange always gives you the getBoundingClientRect of the dropped item.',
'Note, that newIndex = -1 means that item is out of bounds and should be removed.',
'Item 3',
'Item 4',
'Item 5',
'Item 6'
]
};

class RemovableByMove extends React.Component<{}, { items: string[] }> {
state = initialState;
render() {
return (
<div
style={{
maxWidth: '300px',
margin: '0px auto',
backgroundColor: '#F7F7F7',
padding: '3em',
textAlign: 'center'
}}
>
<List
removableByMove
values={this.state.items}
onChange={({ oldIndex, newIndex, targetRect }) => {
console.log(oldIndex, newIndex, targetRect);
this.setState((prevState: { items: string[] }) => ({
items:
newIndex === -1
? arrayRemove(prevState.items, oldIndex)
: arrayMove(prevState.items, oldIndex, newIndex)
}));
}}
renderList={({ children, props, isDragged }) => (
<ul
{...props}
style={{
padding: '0em 0em 1em 0em',
cursor: isDragged ? 'grabbing' : undefined
}}
>
{children}
</ul>
)}
renderItem={({
value,
props,
isDragged,
isSelected,
isOutOfBounds
}) => (
<li
{...props}
style={{
...props.style,
padding: '1.5em',
textAlign: 'left',
margin: '0.5em 0em',
listStyleType: 'none',
cursor: isDragged ? 'grabbing' : 'grab',
border: '2px solid #CCC',
boxShadow: '3px 3px #AAA',
color: '#333',
borderRadius: '5px',
fontFamily: 'Arial, "Helvetica Neue", Helvetica, sans-serif',
backgroundColor:
isDragged || isSelected
? isOutOfBounds
? '#F08080'
: '#EEE'
: '#FFF'
}}
>
{value}
</li>
)}
/>
<button onClick={() => this.setState(initialState)}>Reset</button>
</div>
);
}
}

export default RemovableByMove;
7 changes: 5 additions & 2 deletions flowtypes/List.js.flow
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ declare interface IListProps<Value> {
props: IItemProps,
index?: number,
isDragged: boolean,
isSelected: boolean
isSelected: boolean,
isOutOfBounds: boolean
}) => React.Node;
renderList: (props: {
children: any,
Expand All @@ -35,13 +36,15 @@ declare interface IListProps<Value> {
values: Value[];
onChange: (meta: {
oldIndex: number,
newIndex: number
newIndex: number,
targetRect: ClientRect
}) => mixed;
beforeDrag?: (params: {
elements: HTMLElement[],
index: number
}) => mixed;
transitionDuration?: number;
removableByMove?: boolean;
lockVertically?: boolean;
voiceover?: IVoiceover;
}
Expand Down
47 changes: 40 additions & 7 deletions src/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class List<Value = string> extends React.Component<IProps<Value>> {
afterIndex = -2;
state = {
itemDragged: -1,
itemDraggedOutOfBounds: -1,
selectedItem: -1,
initialX: 0,
initialY: 0,
Expand Down Expand Up @@ -101,6 +102,7 @@ class List<Value = string> extends React.Component<IProps<Value>> {
static defaultProps = {
transitionDuration: 300,
lockVertically: false,
removableByMove: false,
voiceover: {
item: (position: number) =>
`You are currently at a draggable item at position ${position}. Press space bar to lift.`,
Expand Down Expand Up @@ -247,7 +249,11 @@ class List<Value = string> extends React.Component<IProps<Value>> {
);
this.initialYOffset = currentYOffset;
}
this.afterIndex = binarySearch(this.topOffsets, itemVerticalCenter);
if (this.isDraggedItemOutOfBounds() && this.props.removableByMove) {
this.afterIndex = this.topOffsets.length + 1;
} else {
this.afterIndex = binarySearch(this.topOffsets, itemVerticalCenter);
}
this.animateItems(
this.afterIndex === -1 ? 0 : this.afterIndex,
this.state.itemDragged,
Expand Down Expand Up @@ -340,17 +346,41 @@ class List<Value = string> extends React.Component<IProps<Value>> {
});
};

onEnd = (e: Event) => {
isDraggedItemOutOfBounds = () => {
const initialRect = this.getChildren()[
this.state.itemDragged
].getBoundingClientRect();
const targetRect = this.ghostRef.current!.getBoundingClientRect();
if (Math.abs(initialRect.left - targetRect.left) > targetRect.width) {
if (this.state.itemDraggedOutOfBounds === -1) {
this.setState({ itemDraggedOutOfBounds: this.state.itemDragged });
}
return true;
}
if (this.state.itemDraggedOutOfBounds > -1) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was a bit unsure why state is reset here. calling isDraggedItemOutOfBounds a second time is required to get back to default? My first instinct would be to reset after this value is consumed. Interested to learn why this was positioned here

Copy link
Owner Author

@tajo tajo Jul 2, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isDraggedItemOutOfBounds is constantly called when an item is being moved around and then one more time when dropped. In both cases, this.state.isDraggedItemOutOfBounds can be reseted so that's why I put it directly into this method so it can be done only in one place.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When an item is being moved around, it can be be flipped to > -1 and back multiple times.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks!

this.setState({ itemDraggedOutOfBounds: -1 });
}
return false;
};

onEnd = (e: TouchEvent & MouseEvent) => {
e.cancelable && e.preventDefault();
document.removeEventListener('mousemove', this.schdOnMouseMove);
document.removeEventListener('touchmove', this.schdOnTouchMove);
document.removeEventListener('mouseup', this.schdOnEnd);
document.removeEventListener('touchup', this.schdOnEnd);
document.removeEventListener('touchcancel', this.schdOnEnd);
if (this.afterIndex > -1 && this.state.itemDragged !== this.afterIndex) {

const isOutOfBounds = this.isDraggedItemOutOfBounds();
if (
(this.props.removableByMove && isOutOfBounds) ||
(this.afterIndex > -1 && this.state.itemDragged !== this.afterIndex)
) {
this.props.onChange({
oldIndex: this.state.itemDragged,
newIndex: this.afterIndex
newIndex:
this.props.removableByMove && isOutOfBounds ? -1 : this.afterIndex,
targetRect: this.ghostRef.current!.getBoundingClientRect()
});
}
this.getChildren().forEach(item => {
Expand Down Expand Up @@ -380,7 +410,8 @@ class List<Value = string> extends React.Component<IProps<Value>> {
});
this.props.onChange({
oldIndex: selectedItem,
newIndex: this.needle
newIndex: this.needle,
targetRect: this.getChildren()[this.needle].getBoundingClientRect()
});
(this.getChildren()[this.needle] as HTMLElement).focus();
}
Expand Down Expand Up @@ -488,7 +519,8 @@ class List<Value = string> extends React.Component<IProps<Value>> {
props,
index,
isDragged: false,
isSelected
isSelected,
isOutOfBounds: false
});
}),
isDragged: this.state.itemDragged > -1,
Expand All @@ -507,7 +539,8 @@ class List<Value = string> extends React.Component<IProps<Value>> {
},
index: this.state.itemDragged,
isDragged: true,
isSelected: false
isSelected: false,
isOutOfBounds: this.state.itemDraggedOutOfBounds > -1
}),
document.body
)}
Expand Down
8 changes: 7 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface IProps<Value> {
index?: number;
isDragged: boolean;
isSelected: boolean;
isOutOfBounds: boolean;
}) => React.ReactNode;
renderList: (props: {
children: React.ReactNode;
Expand All @@ -33,8 +34,13 @@ export interface IProps<Value> {
};
}) => React.ReactNode;
values: Value[];
onChange: (meta: { oldIndex: number; newIndex: number }) => void;
onChange: (meta: {
oldIndex: number;
newIndex: number;
targetRect: ClientRect;
}) => void;
transitionDuration: number;
removableByMove: boolean;
lockVertically: boolean;
voiceover: IVoiceover;
}
Expand Down