/
Dropzone.tsx
288 lines (242 loc) · 8.07 KB
/
Dropzone.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { DialogActions, DialogType, IConditionResult, IDialogContent,
IDialogResult, IInput, showDialog } from '../actions/notifications';
import { IState } from '../types/IState';
import { ComponentEx, connect, translate } from '../util/ComponentEx';
import { truthy } from '../util/util';
import Icon from './Icon';
import Promise from 'bluebird';
import * as React from 'react';
import * as Redux from 'redux';
import { ThunkDispatch } from 'redux-thunk';
import * as url from 'url';
import { WithTranslation } from 'react-i18next';
export type DropType = 'urls' | 'files';
export interface IBaseProps {
drop: (type: DropType, paths: string[]) => void;
accept: DropType[];
dropText?: string;
clickText?: string;
icon?: string;
clickable?: boolean;
dialogHint?: string;
dialogDefault?: string;
style?: React.CSSProperties;
dragOverlay?: JSX.Element;
}
interface IConnectedProps {}
interface IActionProps {
onShowDialog: (type: DialogType, title: string, content: IDialogContent,
actions: DialogActions) => Promise<IDialogResult>;
}
type DropMode = 'no' | 'url' | 'file' | 'hover' | 'invalid';
interface IComponentState {
dropActive: DropMode;
}
type IProps = IBaseProps & IConnectedProps & IActionProps & WithTranslation;
class Dropzone extends ComponentEx<IProps, IComponentState> {
private mWrapperMode: boolean = false;
private mLeaveDelay: NodeJS.Timer;
constructor(props) {
super(props);
this.initState({
dropActive: 'no',
});
}
public componentWillMount() {
// styling is considerably different depending on whether this is
// a stand-alone control or a wrapper for other controls
this.mWrapperMode = React.Children.count(this.props.children) > 0;
}
public render(): JSX.Element {
const { t, clickable, dragOverlay, style } = this.props;
const classes = [ 'dropzone' ];
if (!this.mWrapperMode) {
classes.push('stand-alone');
} else {
classes.push('wrapper');
}
if (this.state.dropActive === 'hover') {
classes.push('hover-click');
} else if (['no', 'invalid'].indexOf(this.state.dropActive) === -1) {
classes.push('hover-valid');
}
return (
<div
className={classes.join(' ')}
onDragEnter={this.onDragEnter}
onDragOver={this.onDragOver}
onDragLeave={this.onDragLeave}
onDrop={this.onDrop}
onMouseOver={(clickable !== false) ? this.onHover : undefined}
onMouseLeave={(clickable !== false) ? this.onHoverLeave : undefined}
onClick={(clickable !== false) ? this.onClick : undefined}
style={{ ...style, position: 'relative' }}
>
{React.Children.count(this.props.children) > 0
? this.props.children
: this.renderContent()}
{(dragOverlay !== undefined) && (['no', 'invalid'].indexOf(this.state.dropActive) === -1)
? <div className='drag-overlay'>{dragOverlay}</div>
: null}
</div>
);
}
private renderContent(): JSX.Element {
const { t, accept, clickText, dropText, icon } = this.props;
const { dropActive } = this.state;
const acceptList = accept.map(mode => {
return {
urls: t('URL(s)'),
files: t('File(s)'),
}[mode];
});
const clickMode = accept[0] === 'urls'
? t('enter URL')
: t('browse for file');
return (
<div className='dropzone-content'>
{(icon !== undefined) ? <Icon name={icon} /> : null}
{dropActive === 'hover'
? t(clickText || 'Click to {{ clickMode }}', { replace: { clickMode } })
: t(dropText || 'Drop {{ accept }}',
{ replace: { accept: acceptList.join(t(' or ')) } }) }
</div>
);
}
private setDropMode(evt: React.DragEvent<any>) {
let type: DropMode = 'invalid';
if ((evt.dataTransfer.types.indexOf('text/uri-list') !== -1)
&& (this.props.accept.indexOf('urls') !== -1)) {
type = 'url';
} else if ((evt.dataTransfer.types.indexOf('Files') !== -1)
&& (this.props.accept.indexOf('files') !== -1)) {
type = 'file';
}
this.nextState.dropActive = type;
return type !== 'invalid';
}
private onDragEnter = (evt: React.DragEvent<any>) => {
evt.preventDefault();
this.setDropMode(evt);
}
private onDragOver = (evt: React.DragEvent<any>) => {
if (this.state.dropActive === 'invalid') {
return;
}
evt.preventDefault();
evt.stopPropagation();
if (this.mLeaveDelay !== undefined) {
clearTimeout(this.mLeaveDelay);
}
if (this.state.dropActive === 'no') {
this.setDropMode(evt);
}
try {
evt.dataTransfer.dropEffect = this.state.dropActive === 'url'
? 'link'
: 'copy';
} catch (err) {
// continue regardless of error
}
return false;
}
private onDragLeave = (evt: React.DragEvent<any>) => {
if (['no', 'invalid'].indexOf(this.state.dropActive) !== -1) {
return;
}
evt.preventDefault();
if (this.mLeaveDelay !== undefined) {
clearTimeout(this.mLeaveDelay);
}
// delay event on drag leave,
this.mLeaveDelay = setTimeout(() => {
this.nextState.dropActive = 'no';
}, 100);
}
private onDrop = (evt: React.DragEvent<any>) => {
const { accept, drop } = this.props;
evt.preventDefault();
const dropUrl = evt.dataTransfer.getData('Url');
if ((dropUrl !== '') && (accept.indexOf('urls') !== -1)) {
drop('urls', [dropUrl]);
}
if ((evt.dataTransfer.files.length > 0) && (accept.indexOf('files') !== -1)) {
const fileList: string[] = [];
for (let i = 0; i < evt.dataTransfer.files.length; ++i) {
fileList.push((evt.dataTransfer.files.item(i) as any).path);
}
drop('files', fileList);
}
this.nextState.dropActive = 'no';
}
private onHover = (evt) => {
this.nextState.dropActive = 'hover';
}
private onHoverLeave = (evt) => {
this.nextState.dropActive = 'no';
}
private onClick = () => {
const { t, accept, dialogDefault, dialogHint } = this.props;
const clickMode = accept[0];
if (clickMode === 'urls') {
this.props.onShowDialog('info', dialogHint, {
input: [{
id: 'url',
type: 'url',
value: dialogDefault,
}],
condition: this.validateURL,
}, [ { label: 'Cancel' }, { label: 'Download', default: true } ])
.then(result => {
if (result.action === 'Download') {
let inputUrl = result.input.url;
if (!truthy(url.parse(inputUrl).protocol)) {
// no protocol specified
inputUrl = 'https://' + inputUrl;
}
this.props.drop('urls', [inputUrl]);
}
});
} else {
this.context.api.selectFile({
defaultPath: dialogDefault,
title: dialogHint,
}).then(filePath => {
if (filePath !== undefined) {
this.props.drop('files', [filePath]);
}
});
}
}
private hasEmptyInput = (input: IInput): IConditionResult => {
const { t } = this.props;
return (input.value === undefined) || ((input.value === ''))
? {
id: input.id || 'url',
actions: ['Download'],
errorText: t('{{label}} cannot be empty.', {
replace: { label: input.label ? input.label : 'Field' },
}),
}
: undefined;
}
private validateURL = (content: IDialogContent): IConditionResult[] => {
const urlInput = content.input.find(inp => inp.id === 'url');
return [this.hasEmptyInput(urlInput)].filter(res => res !== undefined);
}
}
function mapStateToProps(state): IConnectedProps {
return {
};
}
function mapDispatchToProps(dispatch: ThunkDispatch<any, null, Redux.Action>): IActionProps {
return {
onShowDialog: (type: DialogType, title: string,
content: IDialogContent, actions: DialogActions) =>
dispatch(showDialog(type, title, content, actions)),
};
}
export default
translate(['common'])(
connect<{}, IActionProps, IBaseProps, IState>(mapStateToProps, mapDispatchToProps)(
Dropzone)) as React.ComponentClass<IBaseProps>;