forked from yabwe/medium-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file-dragging.js
87 lines (68 loc) · 2.94 KB
/
file-dragging.js
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
(function () {
'use strict';
var CLASS_DRAG_OVER = 'medium-editor-dragover';
function clearClassNames(element) {
var editable = MediumEditor.util.getContainerEditorElement(element),
existing = Array.prototype.slice.call(editable.parentElement.querySelectorAll('.' + CLASS_DRAG_OVER));
existing.forEach(function (el) {
el.classList.remove(CLASS_DRAG_OVER);
});
}
var FileDragging = MediumEditor.Extension.extend({
name: 'fileDragging',
allowedTypes: ['image'],
init: function () {
MediumEditor.Extension.prototype.init.apply(this, arguments);
this.subscribe('editableDrag', this.handleDrag.bind(this));
this.subscribe('editableDrop', this.handleDrop.bind(this));
},
handleDrag: function (event) {
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
var target = event.target.classList ? event.target : event.target.parentElement;
// Ensure the class gets removed from anything that had it before
clearClassNames(target);
if (event.type === 'dragover') {
target.classList.add(CLASS_DRAG_OVER);
}
},
handleDrop: function (event) {
// Prevent file from opening in the current window
event.preventDefault();
event.stopPropagation();
// IE9 does not support the File API, so prevent file from opening in the window
// but also don't try to actually get the file
if (event.dataTransfer.files) {
Array.prototype.slice.call(event.dataTransfer.files).forEach(function (file) {
if (this.isAllowedFile(file)) {
if (file.type.match('image')) {
this.insertImageFile(file);
}
}
}, this);
}
// Make sure we remove our class from everything
clearClassNames(event.target);
},
isAllowedFile: function (file) {
return this.allowedTypes.some(function (fileType) {
return !!file.type.match(fileType);
});
},
insertImageFile: function (file) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
var id = 'medium-img-' + (+new Date());
MediumEditor.util.insertHTMLCommand(this.document, '<img class="medium-editor-image-loading" id="' + id + '" />');
fileReader.onload = function () {
var img = this.document.getElementById(id);
if (img) {
img.removeAttribute('id');
img.removeAttribute('class');
img.src = fileReader.result;
}
}.bind(this);
}
});
MediumEditor.extensions.fileDragging = FileDragging;
}());