Skip to content

Handle external drops #1

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@ lib
/coverage
yarn.lock
es/

.now
155 changes: 155 additions & 0 deletions examples/external-drops.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/* eslint-disable no-console, react/no-access-state-in-setstate,
react/no-danger, no-param-reassign */
import React from 'react';
import { gData } from './utils/dataUtil';
import '../assets/index.less';
import Tree from '../src';

const STYLE = `
.rc-tree-child-tree {
display: block;
}

.node-motion {
transition: all .3s;
overflow-y: hidden;
}
`;

const motion = {
motionName: 'node-motion',
motionAppear: false,
onAppearStart: node => {
console.log('Start Motion:', node);
return { height: 0 };
},
onAppearActive: node => ({ height: node.scrollHeight }),
onLeaveStart: node => ({ height: node.offsetHeight }),
onLeaveActive: () => ({ height: 0 }),
};

// const gData = [
// { title: '0-0', key: '0-0' },
// { title: '0-1', key: '0-1' },
// { title: '0-2', key: '0-2', children: [{ title: '0-2-0', key: '0-2-0' }] },
// ];

class Demo extends React.Component {
state = {
gData,
autoExpandParent: true,
expandedKeys: ['0-0-key', '0-0-0-key', '0-0-0-0-key'],
};

onDragEnter = ({ expandedKeys }) => {
console.log('enter', expandedKeys);
this.setState({
expandedKeys,
});
};

onDrop = (info, dragObj = null) => {
console.log('drop', info);
const dropKey = info.node.props.eventKey;
const dragKey = info.dragNode.props.eventKey;
const dropPos = info.node.props.pos.split('-');
const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

const loop = (data, key, callback) => {
data.forEach((item, index, arr) => {
if (item.key === key) {
callback(item, index, arr);
return;
}
if (item.children) {
loop(item.children, key, callback);
}
});
};
const data = [...this.state.gData];

// Find dragObject
if (!dragObj) {
loop(data, dragKey, (item, index, arr) => {
arr.splice(index, 1);
dragObj = item;
});
}

if (!info.dropToGap) {
// Drop on the content
loop(data, dropKey, item => {
item.children = item.children || [];
// where to insert 示例添加到尾部,可以是随意位置
item.children.push(dragObj);
});
} else if (
(info.node.props.children || []).length > 0 && // Has children
info.node.props.expanded && // Is expanded
dropPosition === 1 // On the bottom gap
) {
loop(data, dropKey, item => {
item.children = item.children || [];
// where to insert 示例添加到尾部,可以是随意位置
item.children.unshift(dragObj);
});
} else {
// Drop on the gap
let ar;
let i;
loop(data, dropKey, (item, index, arr) => {
ar = arr;
i = index;
});
if (dropPosition === -1) {
ar.splice(i, 0, dragObj);
} else {
ar.splice(i + 1, 0, dragObj);
}
}

this.setState({
gData: data,
});
};

onExpand = expandedKeys => {
console.log('onExpand', expandedKeys);
this.setState({
expandedKeys,
autoExpandParent: false,
});
};

handleExternalDrop = items => {
console.log('onExternalDrop', items);
items.map(item => this.onDrop(item, item.dragNode));
};

render() {
const { expandedKeys } = this.state;

return (
<div className="draggable-demo">
<style dangerouslySetInnerHTML={{ __html: STYLE }} />

<h2>External Drop example (based on animation-draggable)</h2>
<p>drag and drop any item from outside</p>
<Tree
expandedKeys={expandedKeys}
onExpand={this.onExpand}
autoExpandParent={this.state.autoExpandParent}
draggable
onDragStart={this.onDragStart}
onDragEnter={this.onDragEnter}
onDrop={this.onDrop}
treeData={this.state.gData}
motion={motion}
onExternalDrop={this.handleExternalDrop}
/>
</div>
);
}
}

export default Demo;
75 changes: 67 additions & 8 deletions src/Tree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
EventDataNode,
NodeInstance,
ScrollTo,
ExternalDropData,
} from './interface';
import {
flattenTreeData,
Expand Down Expand Up @@ -131,6 +132,7 @@ export interface TreeProps {
dropPosition: number;
dropToGap: boolean;
}) => void;
onExternalDrop?: (nodes: EventDataNode[]) => Promise<void>;
/**
* Used for `rc-tree-select` only.
* Do not use in your production code directly since this will be refactor.
Expand Down Expand Up @@ -414,12 +416,10 @@ class Tree extends React.Component<TreeProps, TreeState> {
const { onDragEnter } = this.props;
const { pos, eventKey } = node.props;

if (!this.dragNode) return;

const dropPosition = calcDropPosition(event, node);

// Skip if drag node is self
if (this.dragNode.props.eventKey === eventKey && dropPosition === 0) {
// // Skip if drag node is self
if (this.dragNode && this.dragNode.props.eventKey === eventKey && dropPosition === 0) {
this.setState({
dragOverNodeKey: '',
dropPosition: null,
Expand Down Expand Up @@ -478,7 +478,7 @@ class Tree extends React.Component<TreeProps, TreeState> {
const { eventKey } = node.props;

// Update drag position
if (this.dragNode && eventKey === this.state.dragOverNodeKey) {
if (eventKey === this.state.dragOverNodeKey) {
const dropPosition = calcDropPosition(event, node);

if (dropPosition === this.state.dropPosition) return;
Expand Down Expand Up @@ -519,10 +519,59 @@ class Tree extends React.Component<TreeProps, TreeState> {
this.dragNode = null;
};

onNodeDrop = (event: React.MouseEvent<HTMLDivElement>, node: NodeInstance) => {
getUniqKey = (s: string) => {
const keys = Object.keys(this.state.keyEntities);
const exists = keys.filter(key => key === s).length > 0;
if (exists) {
return this.getUniqKey(`${s}-1`);
}
return s;
};

createEventNode = (key: string, itemData: ExternalDropData) => {
const uniqueKey = this.getUniqKey(key);
const treeNodeRequiredProps = this.getTreeNodeRequiredProps();
const eventNode = convertNodePropsToEventData({
...getTreeNodeProps(uniqueKey, treeNodeRequiredProps),
data: { key: uniqueKey, ...itemData },
});

return eventNode;
};

handleOutsideDrop = (items: DataTransferItemList, dropResult) => {
dropResult.event.persist();
const { onExternalDrop } = this.props;
const dropResPromises = [];

for (let i = 0; i < items.length; i += 1) {
const { kind, type } = items[i];
const promise = new Promise((resolve: (val: ExternalDropData) => void) => {
if (kind === 'string') {
items[i].getAsString(s => resolve({ title: s, type, kind }));
} else {
const file = items[i].getAsFile();
resolve({ title: file.name, file, kind, type });
}
}).then(data => {
const dragNode = this.createEventNode(`${data.title}-${data.type}`, data);
return {
...dropResult,
dragNode,
};
});

dropResPromises.push(promise);
}

Promise.all(dropResPromises).then(res => onExternalDrop(res));
};

onNodeDrop = (event: React.DragEvent<HTMLDivElement>, node: NodeInstance) => {
const { dragNodesKeys = [], dropPosition } = this.state;
const { onDrop } = this.props;
const { onDrop, onExternalDrop } = this.props;
const { eventKey, pos } = node.props;
const outsideDropData = event.dataTransfer.items;

this.setState({
dragOverNodeKey: '',
Expand All @@ -539,7 +588,7 @@ class Tree extends React.Component<TreeProps, TreeState> {
const dropResult = {
event,
node: convertNodePropsToEventData(node.props),
dragNode: convertNodePropsToEventData(this.dragNode.props),
dragNode: null,
dragNodesKeys: dragNodesKeys.slice(),
dropPosition: dropPosition + Number(posArr[posArr.length - 1]),
dropToGap: false,
Expand All @@ -549,6 +598,16 @@ class Tree extends React.Component<TreeProps, TreeState> {
dropResult.dropToGap = true;
}

if (outsideDropData.length > 0 && onExternalDrop) {
dropResult.event.persist();
this.handleOutsideDrop(outsideDropData, dropResult);
return;
}

if (this.dragNode) {
dropResult.dragNode = convertNodePropsToEventData(this.dragNode.props);
}

if (onDrop) {
onDrop(dropResult);
}
Expand Down
7 changes: 7 additions & 0 deletions src/interface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,10 @@ export interface FlattenNode {
}

export type ScrollTo = (scroll: { key: Key }) => void;

export interface ExternalDropData {
title: string;
kind: string;
type: string;
file?: File;
}
18 changes: 3 additions & 15 deletions src/utils/treeUtil.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import * as React from 'react';
import toArray from 'rc-util/lib/Children/toArray';
import warning from 'rc-util/lib/warning';
import {
DataNode,
FlattenNode,
NodeElement,
DataEntity,
Key,
EventDataNode,
} from '../interface';
import { DataNode, FlattenNode, NodeElement, DataEntity, Key, EventDataNode } from '../interface';
import { getPosition, isTreeNode } from '../util';
import { TreeNodeProps } from '../TreeNode';

Expand Down Expand Up @@ -57,10 +50,7 @@ export function convertTreeToData(rootNodes: React.ReactNode): DataNode[] {
.map(treeNode => {
// Filter invalidate node
if (!isTreeNode(treeNode)) {
warning(
!treeNode,
'Tree/TreeNode can only accept TreeNode as children.',
);
warning(!treeNode, 'Tree/TreeNode can only accept TreeNode as children.');
return null;
}

Expand Down Expand Up @@ -293,9 +283,7 @@ export function getTreeNodeProps(
return treeNodeProps;
}

export function convertNodePropsToEventData(
props: TreeNodeProps,
): EventDataNode {
export function convertNodePropsToEventData(props: TreeNodeProps): EventDataNode {
const {
data,
expanded,
Expand Down