Debian Codegraph @

closure-library/closure/goog/ui/dragdropdetector.js

raw
1 // Copyright 2007 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Detects images dragged and dropped on to the window.
17 *
18 * @author [email protected] (Robby Walker)
19 */
20
21 goog.provide('goog.ui.DragDropDetector');
22 goog.provide('goog.ui.DragDropDetector.EventType');
23 goog.provide('goog.ui.DragDropDetector.ImageDropEvent');
24 goog.provide('goog.ui.DragDropDetector.LinkDropEvent');
25
26 goog.require('goog.dom');
27 goog.require('goog.dom.InputType');
28 goog.require('goog.dom.TagName');
29 goog.require('goog.events.Event');
30 goog.require('goog.events.EventHandler');
31 goog.require('goog.events.EventTarget');
32 goog.require('goog.events.EventType');
33 goog.require('goog.math.Coordinate');
34 goog.require('goog.string');
35 goog.require('goog.style');
36 goog.require('goog.userAgent');
37
38
39
40 /**
41 * Creates a new drag and drop detector.
42 * @param {string=} opt_filePath The URL of the page to use for the detector.
43 * It should contain the same contents as dragdropdetector_target.html in
44 * the demos directory.
45 * @constructor
46 * @extends {goog.events.EventTarget}
47 * @final
48 */
49 goog.ui.DragDropDetector = function(opt_filePath) {
50 goog.ui.DragDropDetector.base(this, 'constructor');
51
52 var iframe = goog.dom.createDom(goog.dom.TagName.IFRAME, {'frameborder': 0});
53 // In Firefox, we do all drop detection with an IFRAME. In IE, we only use
54 // the IFRAME to capture copied, non-linked images. (When we don't need it,
55 // we put a text INPUT before it and push it off screen.)
56 iframe.className = goog.userAgent.IE ?
57 goog.getCssName(
58 goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-editable-iframe') :
59 goog.getCssName(
60 goog.ui.DragDropDetector.BASE_CSS_NAME_, 'w3c-editable-iframe');
61 iframe.src = opt_filePath || goog.ui.DragDropDetector.DEFAULT_FILE_PATH_;
62
63 this.element_ = /** @type {!HTMLIFrameElement} */ (iframe);
64
65 this.handler_ = new goog.events.EventHandler(this);
66 this.handler_.listen(iframe, goog.events.EventType.LOAD, this.initIframe_);
67
68 if (goog.userAgent.IE) {
69 // In IE, we have to bounce between an INPUT for catching links and an
70 // IFRAME for catching images.
71 this.textInput_ = goog.dom.createDom(goog.dom.TagName.INPUT, {
72 'type': goog.dom.InputType.TEXT,
73 'className':
74 goog.getCssName(goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-input')
75 });
76
77 this.root_ = goog.dom.createDom(
78 goog.dom.TagName.DIV,
79 goog.getCssName(goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-div'),
80 this.textInput_, iframe);
81 } else {
82 this.root_ = iframe;
83 }
84
85 document.body.appendChild(this.root_);
86 };
87 goog.inherits(goog.ui.DragDropDetector, goog.events.EventTarget);
88
89
90 /**
91 * Drag and drop event types.
92 * @enum {string}
93 */
94 goog.ui.DragDropDetector.EventType = {
95 IMAGE_DROPPED: 'onimagedrop',
96 LINK_DROPPED: 'onlinkdrop'
97 };
98
99
100 /**
101 * Browser specific drop event type.
102 * @type {string}
103 * @private
104 */
105 goog.ui.DragDropDetector.DROP_EVENT_TYPE_ =
106 goog.userAgent.IE ? goog.events.EventType.DROP : 'dragdrop';
107
108
109 /**
110 * Initial value for clientX and clientY indicating that the location has
111 * never been updated.
112 */
113 goog.ui.DragDropDetector.INIT_POSITION = -10000;
114
115
116 /**
117 * Prefix for all CSS names.
118 * @type {string}
119 * @private
120 */
121 goog.ui.DragDropDetector.BASE_CSS_NAME_ = goog.getCssName('goog-dragdrop');
122
123
124 /**
125 * @desc Message shown to users to inform them that they can't drag and drop
126 * local files.
127 */
128 goog.ui.DragDropDetector.MSG_DRAG_DROP_LOCAL_FILE_ERROR = goog.getMsg(
129 'It is not possible to drag ' +
130 'and drop image files at this time.\nPlease drag an image from your web ' +
131 'browser.');
132
133
134 /**
135 * @desc Message shown to users trying to drag and drop protected images from
136 * Flickr, etc.
137 */
138 goog.ui.DragDropDetector.MSG_DRAG_DROP_PROTECTED_FILE_ERROR = goog.getMsg(
139 'The image you are ' +
140 'trying to drag has been blocked by the hosting site.');
141
142
143 /**
144 * A map of special case information for URLs that cannot be dropped. Each
145 * entry is of the form:
146 * regex: url regex
147 * message: user visible message about this special case
148 * @type {Array<{regex: RegExp, message: string}>}
149 * @private
150 */
151 goog.ui.DragDropDetector.SPECIAL_CASE_URLS_ = [
152 {
153 regex: /^file:\/\/\//,
154 message: goog.ui.DragDropDetector.MSG_DRAG_DROP_LOCAL_FILE_ERROR
155 },
156 {
157 regex: /flickr(.*)spaceball.gif$/,
158 message: goog.ui.DragDropDetector.MSG_DRAG_DROP_PROTECTED_FILE_ERROR
159 }
160 ];
161
162
163 /**
164 * Regex that matches anything that looks kind of like a URL. It matches
165 * nonspacechars://nonspacechars
166 * @type {RegExp}
167 * @private
168 */
169 goog.ui.DragDropDetector.URL_LIKE_REGEX_ = /^\S+:\/\/\S*$/;
170
171
172 /**
173 * Path to the dragdrop.html file.
174 * @type {string}
175 * @private
176 */
177 goog.ui.DragDropDetector.DEFAULT_FILE_PATH_ = 'dragdropdetector_target.html';
178
179
180 /**
181 * Our event handler object.
182 * @type {goog.events.EventHandler<!goog.ui.DragDropDetector>}
183 * @private
184 */
185 goog.ui.DragDropDetector.prototype.handler_;
186
187
188 /**
189 * The root element (the IFRAME on most browsers, the DIV on IE).
190 * @type {Element}
191 * @private
192 */
193 goog.ui.DragDropDetector.prototype.root_;
194
195
196 /**
197 * The text INPUT element used to detect link drops on IE. null on Firefox.
198 * @type {Element}
199 * @private
200 */
201 goog.ui.DragDropDetector.prototype.textInput_;
202
203
204 /**
205 * The iframe element.
206 * @type {HTMLIFrameElement}
207 * @private
208 */
209 goog.ui.DragDropDetector.prototype.element_;
210
211
212 /**
213 * The iframe's window, null if the iframe hasn't loaded yet.
214 * @type {Window}
215 * @private
216 */
217 goog.ui.DragDropDetector.prototype.window_ = null;
218
219
220 /**
221 * The iframe's document, null if the iframe hasn't loaded yet.
222 * @type {Document}
223 * @private
224 */
225 goog.ui.DragDropDetector.prototype.document_ = null;
226
227
228 /**
229 * The iframe's body, null if the iframe hasn't loaded yet.
230 * @type {HTMLBodyElement}
231 * @private
232 */
233 goog.ui.DragDropDetector.prototype.body_ = null;
234
235
236 /**
237 * Whether we are in "screen cover" mode in which the iframe or div is
238 * covering the entire screen.
239 * @type {boolean}
240 * @private
241 */
242 goog.ui.DragDropDetector.prototype.isCoveringScreen_ = false;
243
244
245 /**
246 * The last position of the mouse while dragging.
247 * @type {goog.math.Coordinate}
248 * @private
249 */
250 goog.ui.DragDropDetector.prototype.mousePosition_ = null;
251
252
253 /**
254 * Initialize the iframe after it has loaded.
255 * @private
256 */
257 goog.ui.DragDropDetector.prototype.initIframe_ = function() {
258 // Set up a holder for position data.
259 this.mousePosition_ = new goog.math.Coordinate(
260 goog.ui.DragDropDetector.INIT_POSITION,
261 goog.ui.DragDropDetector.INIT_POSITION);
262
263 // Set up pointers to the important parts of the IFrame.
264 this.window_ = this.element_.contentWindow;
265 this.document_ = this.window_.document;
266 this.body_ = this.document_.body;
267
268 if (goog.userAgent.GECKO) {
269 this.document_.designMode = 'on';
270 } else if (!goog.userAgent.IE) {
271 // Bug 1667110
272 // In IE, we only set the IFrame body as content-editable when we bring it
273 // into view at the top of the page. Otherwise it may take focus when the
274 // page is loaded, scrolling the user far offscreen.
275 // Note that this isn't easily unit-testable, since it depends on a
276 // browser-specific behavior with content-editable areas.
277 this.body_.contentEditable = true;
278 }
279
280 this.handler_.listen(
281 document.body, goog.events.EventType.DRAGENTER, this.coverScreen_);
282
283 if (goog.userAgent.IE) {
284 // IE only events.
285 // Set up events on the IFrame.
286 this.handler_
287 .listen(
288 this.body_,
289 [goog.events.EventType.DRAGENTER, goog.events.EventType.DRAGOVER],
290 goog.ui.DragDropDetector.enforceCopyEffect_)
291 .listen(this.body_, goog.events.EventType.MOUSEOUT, this.switchToInput_)
292 .listen(
293 this.body_, goog.events.EventType.DRAGLEAVE, this.uncoverScreen_)
294 .listen(
295 this.body_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
296 function(e) {
297 this.trackMouse_(e);
298
299 // The drop event occurs before the content is added to the
300 // iframe. We setTimeout so that handleNodeInserted_ is called
301 // after the content is in the document.
302 goog.global.setTimeout(
303 goog.bind(this.handleNodeInserted_, this, e), 0);
304 return true;
305 })
306 .
307
308 // Set up events on the DIV.
309 listen(
310 this.root_,
311 [goog.events.EventType.DRAGENTER, goog.events.EventType.DRAGOVER],
312 this.handleNewDrag_)
313 .listen(
314 this.root_,
315 [goog.events.EventType.MOUSEMOVE, goog.events.EventType.KEYPRESS],
316 this.uncoverScreen_)
317 .
318
319 // Set up events on the text INPUT.
320 listen(
321 this.textInput_, goog.events.EventType.DRAGOVER,
322 goog.events.Event.preventDefault)
323 .listen(
324 this.textInput_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
325 this.handleInputDrop_);
326 } else {
327 // W3C events.
328 this.handler_
329 .listen(
330 this.body_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
331 function(e) {
332 this.trackMouse_(e);
333 this.uncoverScreen_();
334 })
335 .listen(
336 this.body_,
337 [goog.events.EventType.MOUSEMOVE, goog.events.EventType.KEYPRESS],
338 this.uncoverScreen_)
339 // Detect content insertion.
340 .listen(this.document_, 'DOMNodeInserted', this.handleNodeInserted_);
341 }
342 };
343
344
345 /**
346 * Enforce that anything dragged over the IFRAME is copied in to it, rather
347 * than making it navigate to a different URL.
348 * @param {goog.events.BrowserEvent} e The event to enforce copying on.
349 * @private
350 */
351 goog.ui.DragDropDetector.enforceCopyEffect_ = function(e) {
352 var event = e.getBrowserEvent();
353 // This function is only called on IE.
354 if (event.dataTransfer.dropEffect.toLowerCase() != 'copy') {
355 event.dataTransfer.dropEffect = 'copy';
356 }
357 };
358
359
360 /**
361 * Cover the screen with the iframe.
362 * @param {goog.events.BrowserEvent} e The event that caused this function call.
363 * @private
364 */
365 goog.ui.DragDropDetector.prototype.coverScreen_ = function(e) {
366 // Don't do anything if the drop effect is 'none' and we are in IE.
367 // It is set to 'none' in cases like dragging text inside a text area.
368 if (goog.userAgent.IE &&
369 e.getBrowserEvent().dataTransfer.dropEffect == 'none') {
370 return;
371 }
372
373 if (!this.isCoveringScreen_) {
374 this.isCoveringScreen_ = true;
375 if (goog.userAgent.IE) {
376 goog.style.setStyle(this.root_, 'top', '0');
377 this.body_.contentEditable = true;
378 this.switchToInput_(e);
379 } else {
380 goog.style.setStyle(this.root_, 'height', '5000px');
381 }
382 }
383 };
384
385
386 /**
387 * Uncover the screen.
388 * @private
389 */
390 goog.ui.DragDropDetector.prototype.uncoverScreen_ = function() {
391 if (this.isCoveringScreen_) {
392 this.isCoveringScreen_ = false;
393 if (goog.userAgent.IE) {
394 this.body_.contentEditable = false;
395 goog.style.setStyle(this.root_, 'top', '-5000px');
396 } else {
397 goog.style.setStyle(this.root_, 'height', '10px');
398 }
399 }
400 };
401
402
403 /**
404 * Re-insert the INPUT into the DIV. Does nothing when the DIV is off screen.
405 * @param {goog.events.BrowserEvent} e The event that caused this function call.
406 * @private
407 */
408 goog.ui.DragDropDetector.prototype.switchToInput_ = function(e) {
409 // This is only called on IE.
410 if (this.isCoveringScreen_) {
411 goog.style.setElementShown(this.textInput_, true);
412 }
413 };
414
415
416 /**
417 * Remove the text INPUT so the IFRAME is showing. Does nothing when the DIV is
418 * off screen.
419 * @param {goog.events.BrowserEvent} e The event that caused this function call.
420 * @private
421 */
422 goog.ui.DragDropDetector.prototype.switchToIframe_ = function(e) {
423 // This is only called on IE.
424 if (this.isCoveringScreen_) {
425 goog.style.setElementShown(this.textInput_, false);
426 }
427 };
428
429
430 /**
431 * Handle a new drag event.
432 * @param {goog.events.BrowserEvent} e The event object.
433 * @return {boolean|undefined} Returns false in IE to cancel the event.
434 * @private
435 */
436 goog.ui.DragDropDetector.prototype.handleNewDrag_ = function(e) {
437 var event = e.getBrowserEvent();
438
439 // This is only called on IE.
440 if (event.dataTransfer.dropEffect == 'link') {
441 this.switchToInput_(e);
442 e.preventDefault();
443 return false;
444 }
445
446 // Things that aren't links can be placed in the contentEditable iframe.
447 this.switchToIframe_(e);
448
449 // No need to return true since for events return true is the same as no
450 // return.
451 };
452
453
454 /**
455 * Handle mouse tracking.
456 * @param {goog.events.BrowserEvent} e The event object.
457 * @private
458 */
459 goog.ui.DragDropDetector.prototype.trackMouse_ = function(e) {
460 this.mousePosition_.x = e.clientX;
461 this.mousePosition_.y = e.clientY;
462
463 // Check if the event is coming from within the iframe.
464 if (goog.dom.getOwnerDocument(/** @type {Node} */ (e.target)) != document) {
465 var iframePosition = goog.style.getClientPosition(this.element_);
466 this.mousePosition_.x += iframePosition.x;
467 this.mousePosition_.y += iframePosition.y;
468 }
469 };
470
471
472 /**
473 * Handle a drop on the IE text INPUT.
474 * @param {goog.events.BrowserEvent} e The event object.
475 * @private
476 */
477 goog.ui.DragDropDetector.prototype.handleInputDrop_ = function(e) {
478 this.dispatchEvent(
479 new goog.ui.DragDropDetector.LinkDropEvent(
480 e.getBrowserEvent().dataTransfer.getData('Text')));
481 this.uncoverScreen_();
482 e.preventDefault();
483 };
484
485
486 /**
487 * Clear the contents of the iframe.
488 * @private
489 */
490 goog.ui.DragDropDetector.prototype.clearContents_ = function() {
491 if (goog.userAgent.WEBKIT) {
492 // Since this is called on a mutation event for the nodes we are going to
493 // clear, calling this right away crashes some versions of WebKit. Wait
494 // until the events are finished.
495 goog.global.setTimeout(goog.bind(function() {
496 goog.dom.setTextContent(this, '');
497 }, this.body_), 0);
498 } else {
499 this.document_.execCommand('selectAll', false, null);
500 this.document_.execCommand('delete', false, null);
501 this.document_.execCommand('selectAll', false, null);
502 }
503 };
504
505
506 /**
507 * Event handler called when the content of the iframe changes.
508 * @param {goog.events.BrowserEvent} e The event that caused this function call.
509 * @private
510 */
511 goog.ui.DragDropDetector.prototype.handleNodeInserted_ = function(e) {
512 var uri;
513
514 if (this.body_.innerHTML.indexOf('<') == -1) {
515 // If the document contains no tags (i.e. is just text), try it out.
516 uri = goog.string.trim(goog.dom.getTextContent(this.body_));
517
518 // See if it looks kind of like a url.
519 if (!uri.match(goog.ui.DragDropDetector.URL_LIKE_REGEX_)) {
520 uri = null;
521 }
522 }
523
524 if (!uri) {
525 var imgs = goog.dom.getElementsByTagName(goog.dom.TagName.IMG, this.body_);
526 if (imgs && imgs.length) {
527 // TODO(robbyw): Grab all the images, instead of just the first.
528 var img = imgs[0];
529 uri = img.src;
530 }
531 }
532
533 if (uri) {
534 var specialCases = goog.ui.DragDropDetector.SPECIAL_CASE_URLS_;
535 var len = specialCases.length;
536 for (var i = 0; i < len; i++) {
537 var specialCase = specialCases[i];
538 if (uri.match(specialCase.regex)) {
539 alert(specialCase.message);
540 break;
541 }
542 }
543
544 // If no special cases matched, add the image.
545 if (i == len) {
546 this.dispatchEvent(
547 new goog.ui.DragDropDetector.ImageDropEvent(
548 uri, this.mousePosition_));
549 return;
550 }
551 }
552
553 var links = goog.dom.getElementsByTagName(goog.dom.TagName.A, this.body_);
554 if (links) {
555 for (i = 0, len = links.length; i < len; i++) {
556 this.dispatchEvent(
557 new goog.ui.DragDropDetector.LinkDropEvent(links[i].href));
558 }
559 }
560
561 this.clearContents_();
562 this.uncoverScreen_();
563 };
564
565
566 /** @override */
567 goog.ui.DragDropDetector.prototype.disposeInternal = function() {
568 goog.ui.DragDropDetector.base(this, 'disposeInternal');
569 this.handler_.dispose();
570 this.handler_ = null;
571 };
572
573
574
575 /**
576 * Creates a new image drop event object.
577 * @param {string} url The url of the dropped image.
578 * @param {goog.math.Coordinate} position The screen position where the drop
579 * occurred.
580 * @constructor
581 * @extends {goog.events.Event}
582 * @final
583 */
584 goog.ui.DragDropDetector.ImageDropEvent = function(url, position) {
585 goog.ui.DragDropDetector.ImageDropEvent.base(
586 this, 'constructor', goog.ui.DragDropDetector.EventType.IMAGE_DROPPED);
587
588 /**
589 * The url of the image that was dropped.
590 * @type {string}
591 * @private
592 */
593 this.url_ = url;
594
595 /**
596 * The screen position where the drop occurred.
597 * @type {goog.math.Coordinate}
598 * @private
599 */
600 this.position_ = position;
601 };
602 goog.inherits(goog.ui.DragDropDetector.ImageDropEvent, goog.events.Event);
603
604
605 /**
606 * @return {string} The url of the image that was dropped.
607 */
608 goog.ui.DragDropDetector.ImageDropEvent.prototype.getUrl = function() {
609 return this.url_;
610 };
611
612
613 /**
614 * @return {goog.math.Coordinate} The screen position where the drop occurred.
615 * This may be have x and y of goog.ui.DragDropDetector.INIT_POSITION,
616 * indicating the drop position is unknown.
617 */
618 goog.ui.DragDropDetector.ImageDropEvent.prototype.getPosition = function() {
619 return this.position_;
620 };
621
622
623
624 /**
625 * Creates a new link drop event object.
626 * @param {string} url The url of the dropped link.
627 * @constructor
628 * @extends {goog.events.Event}
629 * @final
630 */
631 goog.ui.DragDropDetector.LinkDropEvent = function(url) {
632 goog.ui.DragDropDetector.LinkDropEvent.base(
633 this, 'constructor', goog.ui.DragDropDetector.EventType.LINK_DROPPED);
634
635 /**
636 * The url of the link that was dropped.
637 * @type {string}
638 * @private
639 */
640 this.url_ = url;
641 };
642 goog.inherits(goog.ui.DragDropDetector.LinkDropEvent, goog.events.Event);
643
644
645 /**
646 * @return {string} The url of the link that was dropped.
647 */
648 goog.ui.DragDropDetector.LinkDropEvent.prototype.getUrl = function() {
649 return this.url_;
650 };