forked from ProgerXP/FileDrop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filedrop.js
2527 lines (2207 loc) · 98.7 KB
/
filedrop.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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
FileDrop Revamped - HTML5 & legacy file upload
in public domain | http://filedropjs.org
by Proger_XP | http://proger.me
Supports IE 6+, FF 3.6+, Chrome 7+, Safari 5+, Opera 11+.
Fork & report problems at https://github.com/ProgerXP/FileDrop
*/
;(function (root, init) {
if (typeof define == 'function' && define.amd) {
define(['exports'], function (exports) { init(root, exports) })
} else if (typeof exports !== 'undefined') {
init(root, exports)
} else {
init(root, root.fd = root.fd || {})
}
})(this, function (root, global) {
/***
Global Utility Functions
***/
// Produces random ID (non necessary unique to anything) with given prefix
// or 'fd' if it's not passed.
//
//? randomID() //=> 'fd_9854'
//? randomID('foo') //=> 'foo_1582'
global.randomID = function (prefix) {
return (prefix || 'fd') + '_' + (Math.random() * 10000).toFixed()
}
// Generates random DOM node ID that's unique to this document with given prefix
// or 'fd' if it's not passed.
//
//? randomID() //=> 'fd_9854'
//? randomID('foo') //=> 'foo_1582'
global.uniqueID = function (prefix) {
do { var id = global.randomID(prefix) } while (global.byID(id))
return id
}
// Retrieves DOM element by its ID attribute or returns id itself if it's
// an element.
//
//? byID('foo') //=> <p id="foo">
//? byID('abracadabra!') //=> null
//? byID({foo: 1}) //=> null
//? byID(null) //=> null
//
//? byID(document.createElement('p'))
// //=> <p>
global.byID = function (id) {
return global.isTag(id) ? id : document.getElementById(id)
}
// Checks if given object is a proper DOM node. If tag is passed also
// checks if that DOM node is of the same tag (case-insensitive).
// Returns true or false.
//
//? isTag('foo') //=> false
//? isTag({foo: 1}) //=> false
//? isTag(null) //=> false
//? isTag(window) //=> false
//? isTag(document.body) //=> true
//? isTag(document.body, 'BoDy') //=> true
//? isTag(document.body, 'head') //=> false
//
//? var el = byID('foo') //=> <p id="foo">
// isTag(el, 'p') //=> true
// isTag(el, 'P') //=> true
// isTag(el, 'div') //=> false
// isTag(el, 'DiV') //=> false
//
//? isTag(document.createElement('p'))
// //=> true
//
//? isTag(document.createElement('p'), 'div')
// //=> false
global.isTag = function (element, tag) {
return typeof element == 'object' && element && element.nodeType == 1 &&
( !tag || element.tagName.toUpperCase() == tag.toUpperCase() )
}
// Creates new XMLHttpRequest object. Falls back for ActiveX for IE 6.
// Throws an exception if couldn't succeed (this shouldn't happen these days).
//
//? newXHR() //=> XMLHttpRequest
global.newXHR = function () {
try {
return new XMLHttpRequest
} catch (e) {
// IE 6.
var activex = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP']
for (var i = 0; i < activex.length; i++) {
try {
return new ActiveXObject(activex[i])
} catch (e) {}
}
}
throw 'Cannot create XMLHttpRequest.'
}
// Checks if given value is a native Array object. Note that jQuery and
// other pseudo-arrays are reported as false.
//
//? isArray([]) //=> true
//? isArray([]) //=> true
//? isArray(new Array) //=> true
//? isArray({}) //=> false
//? isArray('foo') //=> false
//? isArray(null) //=> false
//? isArray($('a')) //=> false
//? isArray(arguments) //=> false
//? isArray($('a').toArray()) //=> true
global.isArray = function (value) {
return Object.prototype.toString.call(value) === '[object Array]'
}
// Converts passed value into an array. If value is already an array its
// copy is returned (so changing value later doesn't affect the returned
// clone).
//
// skipFirst, if given, omits specified number of elements from the start.
// Useful for turning arguments into arrays.
//
//? toArray([]) //=> [] (copy)
//? toArray(['foo']) //=> ['foo'] (copy)
//? toArray(['foo'], 1) //=> []
//? toArray(['foo'], 999) //=> []
//? toArray('foo') //=> ['foo']
//? toArray('foo', 1) //=> []
//? toArray('foo', 999) //=> []
//? toArray({foo: 1}) //=> [{foo: 1}]
//? toArray({foo: 1}, 1) //=> []
//? toArray(null) //=> []
//? toArray(new Array('foo', 'bar')) => ['foo', 'bar'] (copy)
//? toArray(new Array('foo', 'bar'), 1) => ['bar']
//? toArray(new Array('foo', 'bar'), 2) => []
//
//? function showMessage(func, line1, line2, ...) {
// window[func](toArray(arguments, 1).join('\n'))
// }
//
// showMessage('confirm', 'It\'s first line.', 'Second line.')
// //=> confirm('It\'s first line.\nSecond line.')
//
// showMessage('alert', 'First', 'Second')
// //=> alert('First\nSecond')
global.toArray = function (value, skipFirst) {
if (value === null || typeof value == 'undefined') {
return []
} else if (!global.isArray(value) && (typeof value != 'object' || !('callee' in value))) {
// Made sure it's not 'arguments'.
value = [value]
}
return Array.prototype.slice.call(value, skipFirst || 0)
}
// Adds an event listener to a DOM element. Works for old IE as well
// as modern W3C-compliant browsers. type is short event name (without
// 'on' prefix). Does nothing if any parameter is invalid.
// Returns the DOM element itself or whatever was given as this argument.
//
//? addEvent(byID('p'), 'mousemove', function () { alert('Whoosh!') })
//? addEvent(window, 'load', function () { alert('Done loading.') })
//
//? addEvent(null, 'blur', function () { }) // nothing.
//? addEvent(window, null, function () { }) // nothing.
//? addEvent(window, 'blur', null) // nothing.
//
//? addEvent(window, 'nonstandard', function () { })
// // works.
global.addEvent = function (element, type, callback) {
if (element && type && callback) {
if (element.attachEvent) {
element['e' + type + callback] = callback
element[type + callback] = function() {
element['e' + type + callback](window.event)
}
element.attachEvent('on' + type, element[type + callback])
} else {
element.addEventListener(type, callback, false)
}
}
return element
}
// Stops propagation and default browser action of an event.
// Works for old IE and modern W3C-compliant browsers.
//
//? byID('p').onmousemove = function (e) { stopEvent(e) }
global.stopEvent = function (event) {
event.cancelBubble = true
event.returnValue = false
event.stopPropagation && event.stopPropagation()
event.preventDefault && event.preventDefault()
return event
}
// Adds or removes HTML class of a DOM element. Keeps old classes.
// element can be either ID string or a DOM node.
// Returns the element (even if ID was passed) or null if passed value
// is neither a string nor a DOM node or if there's no element with
// this ID.
//
//? setClass(byID('p'), 'foo') //=> <p class="... foo">
//? setClass(byID('p'), 'foo', true) // equivalent to above
//? setClass(byID('p'), 'foo', false) //=> <p class="..."> (no 'foo')
//? setClass('anID', 'foo') //=> <a id="anID" class="... foo">
//? setClass('anID', 'foo', false) //=> <a> without 'foo' class
//?
global.setClass = function (element, className, append) {
if ((element = global.byID(element)) && className != null) {
if (typeof append != 'undefined' && !append) {
element.className = element.className.replace(global.classRegExp(className), ' ')
} else if (!global.hasClass(element, className)) {
element.className += ' ' + className
}
}
return element
}
// Determines if given element has class attribute containing the className
// word. Accepts DOM element or ID string. Returns true or false.
// Examples below refer to <p class="cls1 cls2" id="anID">
//
//? hasClass(byID('anID'), 'cls1') //=> true
//? hasClass('anID', 'cls1') // equivalent to above
//? hasClass('anID', 'cls') //=> false
//? hasClass('anID', 'foo') //=> false
//? hasClass('abra!', 'cls1') //=> false (no such element)
//? hasClass('anID', '') //=> false (empty class)
//? hasClass('anID', null) //=> false
//? hasClass('anID', {foo: 1}) //=> false (not a string)
//? hasClass(null, 'foo') //=> false
//? hasClass({foo: 1}, 'foo') //=> false (not a DOM node)
//? hasClass(window, foo) //=> false
global.hasClass = function (element, className) {
return global.classRegExp(className).test( (global.byID(element) || {}).className )
}
// Returns a regular expression suitable for testing of HTML class-like
// strings to find out if it contains a given word or not (it's not as
// simple as a substring match: 'some class' contains words 'some' and
// 'class' but not 'som' and 'cl' or 'ame' and 'ass').
//
// Shouldn't be used for testing multiple words (space-separated) - will
// only match if they are in the same position in testing string which
// doesn't have to be true: classRegExp('some class') would match
// 'this is some class' but won't match 'some of the class'.
//
// Returns a never matching regexp for bad parameter like object or an
// empty string.
//
//? classRegExp('foo') //=> RegExp /(^|\s+)foo(\s+|$)/ig
//? classRegExp('x').test('x y z') //=> true
//? classRegExp('foo bar') // works but not advised
//? classRegExp({foo: 1}) //=> RegExp /$o_O/
//? classRegExp(null) // the same as above
//? classRegExp(window) // the same as above
//? classRegExp(null).test('foo') //=> false (always)
global.classRegExp = function (className) {
if (className == '' || typeof className == 'object') {
return /$o_O/ // never matches.
} else {
return new RegExp('(^|\\s+)' + className + '(\\s+|$)', 'gi')
}
}
// Copies properties from object base to object child. If overwrite
// is passed and true then base's properties will replace those
// in child even if child has its own properties of that name.
// Note that it doesn't clone child, it's edited in-place.
// Also note that defined properties that are 'undefined' on child are
// replaced by base's even if overwrite is false (see examples).
//
// Returns the modified child (first argument).
//
//? extend({common: 1, child: false}, {common: 'foo', base: true})
// //=> {common: 1, child: false, base: true}
//
//? extend({common: 1, child: false}, {common: 'foo', base: true}, true)
// //=> {common: 'foo', child: false, base: true}
//
//? extend({x: undefined}, {x: 1}) //=> {x: 1}
//? extend({x: null}, {x: 1}) //=> {x: null}
//
//? var child = {y: 1}
// extend(child, {x: 1}) === child //=> true (same object)
// console.dir(child) //=> {y: 1, x: 1}
global.extend = function (child, base, overwrite) {
child = child || {}
base = base || {}
for (var prop in base) {
if (overwrite || typeof child[prop] == 'undefined') {
child[prop] = base[prop]
}
}
return child
}
/***
Event Manipulation Functions
***/
// Calls every handler of the passed callback list with given arguments
// and in context of obj or 'this' if it's omitted.
//
// list can be undefined, a single function or an array (non-function members
// are skipped). Throws exception if list is something else.
// args is converted to array with toArray() so it can be a single value,
// an arguments object or something else - see that function for info.
//
// Returns result of the last called function. If any function returns
// a non-null and non-undefined value all following handlers are skipped.
//
//? callAll(function (a) { return a + 'foo' }, 'arg1')
// //=> 'arg1foo'
//? callAll([ function () { } ], ['arg1'])
// // equivalent to above
//
//? var list = [function (a) { return a[0] == 'a' ? a + 'foo' : null },
// function (a) { alert(a) }]
// callAll(list, 'arg1') //=> 'arg1foo' (first handler)
// callAll(list, 'foo') //=> alert('foo') (second handler)
//
//? callAll(function () { alert(this.x) }, [], {x: 'foo'})
// //=> alert('foo')
//
//? callAll(function () { alert(this.x) }).call({x: 'foo'})
// // equivalent to above
//
//? window.onload = function () {
// callAll([...], arguments, window)
// // equivalent to callAll([...], toArray(arguments), window)
// }
global.callAll = function (list, args, obj) {
var res
args = global.toArray(args)
typeof list == 'function' && (list = [list])
if (global.isArray(list)) {
for (var i = 0; i < list.length; i++) {
if (typeof list[i] == 'function') {
res = list[i].apply(obj || this, args)
if (res != null) { break }
}
}
} else if (list) {
throw 'FileDrop event list must be either an Array, Function, undefined or' +
' null but ' + (typeof list) + ' was given.'
}
return res
}
// Calls event handlers attached on given FileDrop object to passed
// event name with arguments. Hands off most work to callAll().
// obj is an object with the 'events' property (object with keys = event
// names and values = arrays of functions).
//
// Before calling handlers of obj looks if global configuration has
// a preview handler specified - if it does then calls that handler
// and if it returns non-null and non-undefined value doesn't call
// obj's handlers but returns that value immediately. After the global
// preview function it checks for object-wise preview - its 'any' event
// handlers which are treated likewise.
// Preview functions are called with event name pushed in front of
// the other event args.
//
//? var obj = {events: { foo: [function (a) { alert(a); return true }] }}
// callAllOfObject(obj, 'foo', 'arg1') //=> true after alert('arg1')
//
//? window.fd.onObjectCall = function (e) { alert(e + ': tee hee'); return false }
// var obj = ... // as above
// callAllOfObject(obj, 'foo', 'arg1') //=> false after alert('foo: tee hee')
//
//? var obj = {events: { any: [function (e) { return false }] }}
// callAllOfObject(obj, 'anyevent')
// // because of the object-wise preview handler that returns false
// // any event we call will return false bypassing its actual handlers.
global.callAllOfObject = function (obj, event, args) {
if (global.logging && global.hasConsole) {
var handlers = obj.events[event] ? obj.events[event].length || 0 : 0
console.info('FileDrop ' + event + ' event (' + handlers + ') args:')
console.dir([args])
}
var preview = [global.onObjectCall].concat(obj.events.any)
var res = global.callAll(preview, [event].concat(global.toArray(args)), obj)
return res != null ? res : global.callAll(obj.events[event], args, obj)
}
// Appends event listeners to given object with 'events' property according
// to passed parameters. See DropHandle.event() for details.
// 'this' must be set to the object which events are updated.
global.appendEventsToObject = function (events, funcs) {
if (global.addEventsToObject(this, false, arguments)) {
return this
}
switch (arguments.length) {
case 0:
return global.extend({}, this.events)
case 1:
if (events === null) {
this.events = {}
return this
} else if (global.isArray(events)) {
var res = {}
for (var i = 0; i < events.length; i++) {
res[events[i]] = global.toArray(this.events[events[i]])
}
return res
} else if (typeof events == 'function') {
return global.funcNS(events)
} else if (typeof events == 'string') {
return global.toArray(this.events[events])
}
case 2:
events = global.toArray(events)
if (funcs === null) {
for (var i = 0; i < events.length; i++) {
var ns = global.splitNS(events[i])
if (!ns[0]) {
for (var event in this.events) {
arguments.callee.call(this, [event + ':' + ns[1]], null)
}
} else if (!ns[1]) {
this.events[ns[0]] = []
} else if (this.events[ns[0]]) {
for (var fi = this.events[ns[0]].length - 1; fi >= 0; fi--) {
if (global.funcNS( this.events[ns[0]][fi] ) == ns[1]) {
this.events[ns[0]].splice(fi, 1)
}
}
}
}
return this
}
}
throw 'Bad parameters for FileDrop event().'
}
// Prepends event listeners to given object with 'events' property according
// to passed parameters. See DropHandle.event() for details.
// 'this' must be set to the object which events are updated.
global.previewToObject = function (events, funcs) {
if (global.addEventsToObject(this, true, arguments)) {
return this
} else {
throw 'Bad parameters for FileDrop preview().'
}
}
// Adds event listeners to given object with 'events' property according
// to passed parameters. See DropHandle.event() for details.
// Returns nothing if couldn't handle given parameter combination.
global.addEventsToObject = function (obj, prepend, args) {
var events = args[0]
var funcs = args[1]
switch (args.length) {
case 1:
if (events && typeof events == 'object' && !global.isArray(events)) {
for (var event in events) {
arguments.callee(obj, prepend, [event, events[event]])
}
return true
}
case 2:
if (typeof funcs == 'function' || global.isArray(funcs)) {
events = global.toArray(events)
funcs = global.toArray(funcs)
var pusher = prepend ? 'unshift' : 'push'
for (var i = 0; i < events.length; i++) {
var ns = global.splitNS(events[i])
for (var fi = 0; fi < funcs.length; fi++) {
global.funcNS(funcs[fi], ns[1])
}
obj.events[ns[0]] = obj.events[ns[0]] || []
obj.events[ns[0]][pusher].apply(obj.events[ns[0]], funcs)
}
return true
}
}
}
// Adds namespace identifier to a Function object. Used when labeling event
// listeners in DropHandle.event(). If given just one parameter reads
// attached namespace, if present.
//
//? funcNS(function () { }, 'foo')
//? funcNS(function () { }) //=> 'foo'
global.funcNS = function (func, ns) {
if (typeof func != 'function') {
return func
} else if (arguments.length == 1) {
return (func[global.nsProp] || '').toString()
} else {
func[global.nsProp] = (ns || '').toString()
return func
}
}
// Extracts namespace identifier from the string. Uses jQuery notation:
// 'event:namespace'. Both parts can be empty. If colon is omitted returns
// '' instead of namespace.
// Returns array with two items - event name (or other prefix) and namespace.
//
//? splitNS('') //=> ['', '']
//? splitNS(null) // identical to above
//? splitNS(':') // identical to above
//? splitNS('x:') //=> ['x', '']
//? splitNS(':y') //=> ['', 'y']
//? splitNS('x:y') //=> ['x', 'y']
//? splitNS('x:y:z') //=> ['x', 'y:z']
global.splitNS = function (str) {
return (str || '').match(/^([^:]*):?(.*)$/).slice(1)
}
/***
Global Configuration
***/
global.extend(global, {
// If set all event calls will be logged to console if one is present.
logging: true,
// Indicates if console.log and console.dir are available for usage.
hasConsole: 'console' in window && console.log && console.dir,
// If set must be a function that's called on every event being fired.
// See how it works in callAllOfObject().
onObjectCall: null,
// All DropHandle objects that were instantinated on this page.
// Note that these are not FileDrop instances as not all DropHandles
// might be part of FileDrops. Use DropHandle.filedrop property.
all: [],
// Tests for IE versions, must be true for 6-7/9 and below and
// false for any other version/browser.
// IE 6 on XP SP 3 gives JScript version 5.7 while IE 8 - 5.8.
// IE 9 on Win7 gives 9.
isIE6: /*@cc_on/*@if(@_jscript_version<=5.7)true@else@*/false/*@end@*/,
isIE9: /*@cc_on/*@if(@_jscript_version<=9)true@else@*/false/*@end@*/,
// Test for Google Chrome. This isn't used to determine available
// File API but only to work around certain event glitches.
isChrome: (navigator.vendor || '').indexOf('Google') != -1,
// Name of Function object property where event namespace is stored.
// See funcNS(), splitNS(), DropHandle.event().
nsProp: '_fdns'
})
/***
Basic Drop Handle Class
***
Has some file upload functionality (mostly legacy <iframe>) but is mainly
used to handle all drag & drop operations in a cross-browser way.
You can use it as a basis for your own component.
Main FileDrop class extends it and listens for produced drop events.
***/
// Parameters:
// * zone - ID or DOM element which accepts drag & drop. This is often a
// <fieldset>. If such element doesn't exist an exception is thrown
// when trying to create the class. DropHandle will add some children
// to this element to facilitate external drop events. Once created this
// element is accessible as (new DropHandle(...)).el property.
//
// * opt - object, key/value pairs of options. See the code for the list of
// keys and their purpose. Can be omitted or empty to use defaults.
// Current option values are accessible as the opt property.
//
//? new fd.DropHandle('anID')
//? new fd.DropHandle(document.body, {zoneClass: 'with-filedrop'})
global.DropHandle = function (zone, opt) {
// Persistent 'this' instance reference.
var self = this
self.el = zone = global.byID(zone)
if (!zone) { throw 'Cannot locate DOM node given to new FileDrop class.' }
/***
DropHandle Options
***
Changing these on runtime after the class was created doesn't affect
anything so make sure to pass desired values to the constructor.
***/
self.opt = {
// The zone element gets this HTML class appended immediately after
// the DropHandle object is created.
zoneClass: 'fd-zone',
// DropHandle creates a hidden form and <input type="file">. The input
// is completely transparent so the contents underneath is visible
// but at the same time a dropped object lands on the input triggering
// its DOM events. This option specifies the class name assigned
// to this input.
inputClass: 'fd-file',
// Options for fallback upload via <iframe> for browsers lacking
// native drag & drop support - IE and others.
iframe: {
// URL to send uploaded file to. It's a regular form upload with
// enctype="multipart/form-data" so if you're using PHP it's handled
// with $_FILES as usual. The URL can have query string. It will have
// the 'fd-callback' parameter appended containing the name of
// function your server script must call when generating JavaScript
// output - if it does the upload succeeds, otherwise it "fails".
// Calling external function is the only reliable way to know that
// we've uploaded the file right. Plus you can pass any data to
// that function as its parameters.
// For the practical server-side example see included upload.php.
//
// If unset <iframe> upload is disabled so only drag & drop-aware
// browsers (Firefox and Crhome-based) will handle this drop zone.
url: '',
// Name of GET input variable containing the name of the global window
// callback function to be called by the server in the generated
// page after uploading a file via <iframe>.
callbackParam: 'fd-callback',
// Name of POST file input variable (<input type="file" name="$nameParam">).
// Maps to $_FILE[] in PHP.
fileParam: 'fd-file'
},
// Contains DOM nodes of fallback upload via <iframe>. If null necessary
// elements for <iframe> upload will be created automatically.
//
// If this is false (boolean) then DropHandle creates no input at all.
// This is useful if you need pure drag & drop upload that works in
// Firefox and Chrome-based browsers, no <iframe> uploads for IE 9-,
// Opera, Safari and others. This creates "perfect" drop zone that
// doesn't prevent user interaction with underlying components so the
// zone can be extended onto large document area or the entire window.
input: null,
// After construction opt.input's structure is as follows: {
// If unset DropHandle will first recursively look for <input type="file">
// among the children of the zone element and having opt.inputClass among
// its HTML classes. If found no new element will be created. This makes it
// safe to create multiple DropHandle objects for the same zone handle (not
// tested though).
//
// If unset but no suitable node would be found (see above) then DropHandle
// creates the input automatically along with the form which is usually
// exactly what you need.
//file: null,
// This value is set to match the parent form of <input type="file">.
// Changing it isn't recommended.
//form: null
//},
// If using <input type="file"> (legacy <iframe> upload, see input option)
// some browsers including IE 6-10 and Opera will keep last selected file
// in the input after upload which will prevent the user from uploading
// the same file twice in a row (this doesn't apply to drag & drop uploads).
// When enabled, this option will let FileDrop recreate the file input
// thus resetting file selection. This is safe in most cases but if your
// project does some extra customization on opt.input.file this might erase
// them and attached events unless you are doing that in inputSetup event.
// When disabled, input will be cleared in Firefox/Chrome thus preventing
// user from reuploading the same file one after another in other browsers.
recreateInput: true,
// Chrome, unlike Firefox, dispatches drag events for the entire document
// rather than the input element. For Chrome this option is always true.
// If you want the same behaviout in Firefox then you can manually set
// it to true to let all of your drop zones receive drag events as soon
// as they enter the browser's window but not those zones' boundaries.
// Note that drop events (when user releases the mouse button) are always
// dispatched to drop zone under the mouse pointer, if there's any.
// This only makes drag (hover) events fire for all zones regardless of
// the pointer position.
fullDocDragDetect: false,
// Initial state of the multiple selection in browser's Open File dialog
// appearing when clickin on the drop zone (<input type="file">).
// After this object was created toggle this setting with this.multiple().
multiple: false,
// Cursor displayed when a user drags an object over this drop zone.
// Working values depend on the browser. 'copy' and 'none' work for
// Firefox and Chrome; the latter also supports 'move', 'link'.
// Setting to 'none' will cause "No Drop" cursor and will cause drop
// operation to be ignored on this drop zone (on-drop event not fired).
// This option can be set on runtime.
dropEffect: 'copy'
}
// Keeping track of all DropHandle instances.
global.all.push(self)
// If this DropHandle was created by a FileDrop instance this property
// will point to that instance.
self.filedrop = null
var iframe = self.opt.iframe
global.extend(self.opt, opt, true)
// In case user options contained {iframe} without full set of properties.
global.extend(self.opt.iframe, iframe)
// Chrome dispatches drop events document-wise rather than zone-wise.
// If unset we won't receive any reaction on individual elements.
global.isChrome && (self.opt.fullDocDragDetect = true)
/***
DropHandle Events
***
Attach new listeners with (new DropHandle).event('dragEnter', function ...).
As a low-level alternative you can change/move items around this array
directly but it's not future-proof.
Note that all callbacks are executed with 'this' pointing to this
object so it's easy to know which DropHandle has caused that particular
event. For example:
var dh = new DropHandle('myzone')
dh.event('dragEnter', function () {
alert('Entering the ' + this.el.id + ' drop zone!')
})
***/
self.events = {
// Object-wise event preview handlers. They get executed on any event
// of this object (like dragEnter) and if any of them returns a non-null
// and non-undefined value actual event handlers are not called and
// that value is returned. These callbacks receive the same arguments
// as the target event plus that event's name in front.
// See callAllOfObject() for more details.
any: [],
// Occurs when a user drags something across this zone element (Firefox)
// or across the entire browser window (Chrome or if opt.fullDocDragDetect
// is set).
//
// function (eventObject)
dragEnter: [],
// Occurs when user drags the object away from the zone element (Firefox)
// or outside of the window (Chrome or opt.fullDocDragDetect).
//
// function (eventObject)
dragLeave: [],
// Occurs periodically after dragEnter while user is still dragging an
// object inside the drop zone. If not using DropHandle be aware that
// Chrome requires a listener attached to ondragover or it will discard
// the drop operation. DropHandle takes care of this for you.
//
// function (eventObject)
dragOver: [],
// The following 2 events are somewhat superficient and not really useful
// or working but they're still listened to in case you need to hook them.
//
// function (eventObject)
dragEnd: [],
dragExit: [],
// Occurs when a file has been dropped on the zone element or when a file
// was selected in/dropped onto fallback <form> to trigger <iframe> upload.
// The former occurs in Firefox and Chrome-based browsers that support
// drag & drop natively. The latter occurs in Opera and others that only
// work with regular form file uploads.
//
// function (eventObject)
// - is passed native browser-dependent event object.
upload: [],
// Occurs when another DropHandle object on the page initiates upload
// event. Can be used to reset some visual state of all drop zones but
// the one that's actually got the file landed.
//
// function (DropHandle)
// - is passed another DropHandle object that has initiated the
// upload event.
uploadElsewhere: [],
// Occurs after <input type="file"> used to accept file drops was created
// or found (see the description of the 'input' option). Here it's used to
// assign it some HTML classes. You can do similar setup.
// Is also fired after recreating file input on upload if opt.recreateInput
// is set - in this case is passed old <input type="file"> (that was cloned).
//
// function ({ file: DOM_Input, form: DOM_Form }, oldFileInput)
// - is passed an object with the same keys as 'input' option -
// the DOM element of the <input type="file"> and its parent
// <form> DOM element.
inputSetup: [],
// Occurs when a fallback <iframe> element was created. Can be used for
// setup actions similar to inputSetup.
//
// function (DOM_Iframe)
// - is passed the DOM element of the new <iframe>.
iframeSetup: [],
// Occurs when a file was successfully uploaded to the server, i.e.
// when the form was submitted and the server has returned the output
// that calls 'fd-callback' function to indicate successful (or unsuccessful)
// upload to the client page. See the 'iframe' option and included upload.php
// for samples and explanations.
//
// function (response)
// - is passed the same data as given by the server-generated JavaScript
// to the global 'fd-callback'. Note that it's the first argument to
// that function, all others are ignored.
// This object will mimic some of XMLHttpRequest properties so you
// can use single handler for both XHR and <iframe> uploads - see
// sendViaIFrame() for details.
iframeDone: []
}
// Old FireDrop compatibility. Now deprecated.
self.on = self.events
self.zone = self.el
/***
DropHandle Methods
***/
// Prepares target DOM element for drag & drop and <iframe> uploads by
// adding more child nodes and listening to appropriate events.
// Usually you don't need to call this function since it's automatically
// called for the zone element (given to the constructor).
//
//? hook(byID('myzone'))
self.hook = function (zoneNode) {
// If <input type="file"> support was turned off then we're not aiming
// for the support of uploads without File API, i.e. via <iframe> for
// all but Firefox and Chrome. If such we're not creating the form and
// other supportive elements.
if (self.opt.input != false) {
self.opt.input = self.opt.input || self.prepareInput(zoneNode)
self.opt.input && global.callAllOfObject(self, 'inputSetup', self.opt.input)
}
self.hookDragOn(zoneNode)
self.hookDropOn(zoneNode)
}
// Attaches listeners for drag events - when an object is moved in or out
// the scope of the zone element (or document for Chrome). This provides
// common layer for various browser-specific ways to utilize drag* events.
// Once a suitable event occurs DropHandle's own event callbacks are invoked.
self.hookDragOn = function (zoneNode) {
// With dragenter we detect when user moves object over our zone or
// document window to display some feedback.
//
// With dragleave we do the opposite and restore previous component state
// when an object is being moved away or drag & drop is cancelled.
if (self.opt.fullDocDragDetect) {
self.delegate(document.body, 'dragEnter')
global.addEvent(document, 'dragleave', function (e) {
// Chrome (at least in earlier versions) fires dragleave randomly,
// this is used to normalize it to just one real occurrence.
if ((e.clientX == 0 && e.clientY == 0) || global.isTag(e.relatedTarget, 'html')) {
global.stopEvent(e)
global.callAllOfObject(self, 'dragLeave', e)
}
})
} else {
self.delegate(zoneNode, 'dragEnter')
self.delegate(zoneNode, 'dragLeave')
}
self.delegate(zoneNode, 'dragOver')
self.delegate(zoneNode, 'dragEnd') // doesn't work anywhere; unused by FileDrop.
self.delegate(zoneNode, 'dragExit') // works in Firefox; unused by FileDrop.
}
// Attaches listeners to drop events. Just like hookDragOn provides
// common browser-independent ground by normalizing occurred events
// and calling DropHandle's own event handlers.
self.hookDropOn = function (zoneNode) {
// IE 6-9 fire 'drop' event if you drop a file onto a file input. However,
// if the form is submitted after this event IE will send empty POST body
// instead of the actual file data. So handling of this event is disabled here
// although technically it could've worked since IE 6 if not for that bug (?).
//
// Firefox and Chrome-based browsers are the only ones supporting this
// event which we use to read dropped file data in the FileDrop class.
global.isIE9 || self.delegate(zoneNode, 'drop', 'upload')
}
// Listens for DOM events and initiates corresponding DropHandle's events.
// Third argument can specify DropHandle's event name if it differs from
// the DOM event. Propagation of caught events is stopped.
//
//? delegate(byID('myzone'), 'dragleave')
//? delegate(byID('myzone'), 'drop', 'upload')
self.delegate = function (zoneNode, domEvent, selfEvent) {
global.addEvent(zoneNode, domEvent.toLowerCase(), function (e) {
global.stopEvent(e)
global.callAllOfObject(self, selfEvent || domEvent, e)
})
}
// Finds or creates <input type="file"> used to facilitate non-drag & drop
// uploads for browsers othat than Firefox and Chrome-based.
// Returns that input's DOM element and its parent <form> or, if none,
// throws an exception since there's no meaning in having <input type="file">
// and no <form> as both are only reuqired for fallback <iframe> upload.
// This result is assigned to 'input' option.
self.prepareInput = function (parent) {
var file = self.findInputRecursive(parent) || self.createInputAt(parent)
if (file) {
var form = file.parentNode
while (form && !global.isTag(form, 'form')) {
form = form.parentNode
}
if (!form) { throw 'FileDrop file input has no parent form element.' }
// See if the located form has proper target and if that target
// (supposedly <iframe>) really exists - we don't want to reload
// the entire document on file upload since it defeats the purpose
// of AJAX and is probably an error condition.
var target = form ? form.getAttribute('target') : ''
if (target && global.isTag(global.byID(target), 'iframe')) {
// Once here it means the setup is good to go. Return with success.
return {file: file, form: form}
}
}
// Similarly to opt.input == false this means there's input/form found
// so turn off <iframe> upload or create our own elements.
return false
}
// Searches for <input type="file"> containing HTML class opt.inputClass
// among the children of parent. Is used to autodetect pre-created input
// of a drop zone. parent must be a DOM element.
// Returns DOM element or null.
//
//? // <form id="myzone"><input type="file" class="fd-input"></form>
// findInputRecursive(byID('myzone'))
// //=> <input type="file" class="fd-input">
//
//? findInputRecursive(byID('foo')) //=> null
self.findInputRecursive = function (parent) {
for (var i = 0; i < parent.childNodes.length; i++) {
var node = parent.childNodes[i]
if (global.isTag(node, 'input') && node.getAttribute('type') == 'file' &&
global.hasClass(node, self.opt.inputClass)) {
return node
} else if (node = arguments.callee(node)) {
return node
}
}
}
// Creates elements necessary for <iframe> upload to work - the input,
// form and iframe itself. A random unique ID is generated and assigned to
// the iframe, plus new form's target attribute. Once <input type="file">
// gets clicked (and file chosen in the appeared dialog) or once it gets
// a file dropped onto (supported by some browsers) its onchange event
// occurs which we're intercepting in hookDropOn(). With that we trigger
// <form> submission which sends data to our hidden <iframe>. Just like
// old times.
//
// Returns the DOM element of (new) <input type="file">.