forked from react-grid-layout/react-draggable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-draggable.js
2746 lines (2308 loc) · 92.3 KB
/
react-draggable.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
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react-dom"), require("react"));
else if(typeof define === 'function' && define.amd)
define(["react-dom", "react"], factory);
else if(typeof exports === 'object')
exports["ReactDraggable"] = factory(require("react-dom"), require("react"));
else
root["ReactDraggable"] = factory(root["ReactDOM"], root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_6__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 12);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findInArray = findInArray;
exports.isFunction = isFunction;
exports.isNum = isNum;
exports.int = int;
exports.dontSetMe = dontSetMe;
// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc
function findInArray(array /*: Array<any> | TouchList*/, callback /*: Function*/) /*: any*/ {
for (var i = 0, length = array.length; i < length; i++) {
if (callback.apply(callback, [array[i], i, array])) return array[i];
}
}
function isFunction(func /*: any*/) /*: boolean*/ {
return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';
}
function isNum(num /*: any*/) /*: boolean*/ {
return typeof num === 'number' && !isNaN(num);
}
function int(a /*: string*/) /*: number*/ {
return parseInt(a, 10);
}
function dontSetMe(props /*: Object*/, propName /*: string*/, componentName /*: string*/) {
if (props[propName]) {
return new Error('Invalid prop ' + propName + ' passed to ' + componentName + ' - do not set this, set it on the child.');
}
}
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (Object({"DRAGGABLE_DEBUG":undefined}).NODE_ENV !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_4__;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.matchesSelector = matchesSelector;
exports.matchesSelectorAndParentsTo = matchesSelectorAndParentsTo;
exports.addEvent = addEvent;
exports.removeEvent = removeEvent;
exports.outerHeight = outerHeight;
exports.outerWidth = outerWidth;
exports.innerHeight = innerHeight;
exports.innerWidth = innerWidth;
exports.offsetXYFromParent = offsetXYFromParent;
exports.createCSSTransform = createCSSTransform;
exports.createSVGTransform = createSVGTransform;
exports.getTouch = getTouch;
exports.getTouchIdentifier = getTouchIdentifier;
exports.addUserSelectStyles = addUserSelectStyles;
exports.removeUserSelectStyles = removeUserSelectStyles;
exports.styleHacks = styleHacks;
exports.addClassName = addClassName;
exports.removeClassName = removeClassName;
var _shims = __webpack_require__(0);
var _getPrefix = __webpack_require__(19);
var _getPrefix2 = _interopRequireDefault(_getPrefix);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/*:: import type {ControlPosition, MouseTouchEvent} from './types';*/
var matchesSelectorFunc = '';
function matchesSelector(el /*: Node*/, selector /*: string*/) /*: boolean*/ {
if (!matchesSelectorFunc) {
matchesSelectorFunc = (0, _shims.findInArray)(['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'], function (method) {
// $FlowIgnore: Doesn't think elements are indexable
return (0, _shims.isFunction)(el[method]);
});
}
// Might not be found entirely (not an Element?) - in that case, bail
// $FlowIgnore: Doesn't think elements are indexable
if (!(0, _shims.isFunction)(el[matchesSelectorFunc])) return false;
// $FlowIgnore: Doesn't think elements are indexable
return el[matchesSelectorFunc](selector);
}
// Works up the tree to the draggable itself attempting to match selector.
function matchesSelectorAndParentsTo(el /*: Node*/, selector /*: string*/, baseNode /*: Node*/) /*: boolean*/ {
var node = el;
do {
if (matchesSelector(node, selector)) return true;
if (node === baseNode) return false;
node = node.parentNode;
} while (node);
return false;
}
function addEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/) /*: void*/ {
if (!el) {
return;
}
if (el.attachEvent) {
el.attachEvent('on' + event, handler);
} else if (el.addEventListener) {
el.addEventListener(event, handler, true);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = handler;
}
}
function removeEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/) /*: void*/ {
if (!el) {
return;
}
if (el.detachEvent) {
el.detachEvent('on' + event, handler);
} else if (el.removeEventListener) {
el.removeEventListener(event, handler, true);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = null;
}
}
function outerHeight(node /*: HTMLElement*/) /*: number*/ {
// This is deliberately excluding margin for our calculations, since we are using
// offsetTop which is including margin. See getBoundPosition
var height = node.clientHeight;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height += (0, _shims.int)(computedStyle.borderTopWidth);
height += (0, _shims.int)(computedStyle.borderBottomWidth);
return height;
}
function outerWidth(node /*: HTMLElement*/) /*: number*/ {
// This is deliberately excluding margin for our calculations, since we are using
// offsetLeft which is including margin. See getBoundPosition
var width = node.clientWidth;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width += (0, _shims.int)(computedStyle.borderLeftWidth);
width += (0, _shims.int)(computedStyle.borderRightWidth);
return width;
}
function innerHeight(node /*: HTMLElement*/) /*: number*/ {
var height = node.clientHeight;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height -= (0, _shims.int)(computedStyle.paddingTop);
height -= (0, _shims.int)(computedStyle.paddingBottom);
return height;
}
function innerWidth(node /*: HTMLElement*/) /*: number*/ {
var width = node.clientWidth;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width -= (0, _shims.int)(computedStyle.paddingLeft);
width -= (0, _shims.int)(computedStyle.paddingRight);
return width;
}
// Get from offsetParent
function offsetXYFromParent(evt /*: {clientX: number, clientY: number}*/, offsetParent /*: HTMLElement*/) /*: ControlPosition*/ {
var isBody = offsetParent === offsetParent.ownerDocument.body;
var offsetParentRect = isBody ? { left: 0, top: 0 } : offsetParent.getBoundingClientRect();
var x = evt.clientX + offsetParent.scrollLeft - offsetParentRect.left;
var y = evt.clientY + offsetParent.scrollTop - offsetParentRect.top;
return { x: x, y: y };
}
function createCSSTransform(_ref) /*: Object*/ {
var x = _ref.x,
y = _ref.y;
// Replace unitless items with px
return _defineProperty({}, (0, _getPrefix.browserPrefixToKey)('transform', _getPrefix2.default), 'translate(' + x + 'px,' + y + 'px)');
}
function createSVGTransform(_ref3) /*: string*/ {
var x = _ref3.x,
y = _ref3.y;
return 'translate(' + x + ',' + y + ')';
}
function getTouch(e /*: MouseTouchEvent*/, identifier /*: number*/) /*: ?{clientX: number, clientY: number}*/ {
return e.targetTouches && (0, _shims.findInArray)(e.targetTouches, function (t) {
return identifier === t.identifier;
}) || e.changedTouches && (0, _shims.findInArray)(e.changedTouches, function (t) {
return identifier === t.identifier;
});
}
function getTouchIdentifier(e /*: MouseTouchEvent*/) /*: ?number*/ {
if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;
if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;
}
// User-select Hacks:
//
// Useful for preventing blue highlights all over everything when dragging.
// Note we're passing `document` b/c we could be iframed
function addUserSelectStyles(doc /*: ?Document*/) {
if (!doc) return;
var styleEl = doc.getElementById('react-draggable-style-el');
if (!styleEl) {
styleEl = doc.createElement('style');
styleEl.type = 'text/css';
styleEl.id = 'react-draggable-style-el';
styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {background: transparent;}\n';
styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {background: transparent;}\n';
doc.getElementsByTagName('head')[0].appendChild(styleEl);
}
if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');
}
function removeUserSelectStyles(doc /*: ?Document*/) {
try {
if (doc && doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');
window.getSelection().removeAllRanges(); // remove selection caused by scroll
} catch (e) {
// probably IE
}
}
function styleHacks() /*: Object*/ {
var childStyle /*: Object*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// Workaround IE pointer events; see #51
// https://github.com/mzabriskie/react-draggable/issues/51#issuecomment-103488278
return _extends({
touchAction: 'none'
}, childStyle);
}
function addClassName(el /*: HTMLElement*/, className /*: string*/) {
if (el.classList) {
el.classList.add(className);
} else {
if (!el.className.match(new RegExp('(?:^|\\s)' + className + '(?!\\S)'))) {
el.className += ' ' + className;
}
}
}
function removeClassName(el /*: HTMLElement*/, className /*: string*/) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(?:^|\\s)' + className + '(?!\\S)', 'g'), '');
}
}
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_6__;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (Object({"DRAGGABLE_DEBUG":undefined}).NODE_ENV !== 'production') {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = __webpack_require__(14)(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(17)();
}
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var emptyFunction = __webpack_require__(1);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (Object({"DRAGGABLE_DEBUG":undefined}).NODE_ENV !== 'production') {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
module.exports = warning;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getBoundPosition = getBoundPosition;
exports.snapToGrid = snapToGrid;
exports.canDragX = canDragX;
exports.canDragY = canDragY;
exports.getControlPosition = getControlPosition;
exports.createCoreData = createCoreData;
exports.createDraggableData = createDraggableData;
var _shims = __webpack_require__(0);
var _reactDom = __webpack_require__(4);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _domFns = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*:: import type Draggable from '../Draggable';*/
/*:: import type {Bounds, ControlPosition, DraggableData, MouseTouchEvent} from './types';*/
/*:: import type DraggableCore from '../DraggableCore';*/
function getBoundPosition(draggable /*: Draggable*/, x /*: number*/, y /*: number*/) /*: [number, number]*/ {
// If no bounds, short-circuit and move on
if (!draggable.props.bounds) return [x, y];
// Clone new bounds
var bounds = draggable.props.bounds;
bounds = typeof bounds === 'string' ? bounds : cloneBounds(bounds);
var node = findDOMNode(draggable);
if (typeof bounds === 'string') {
var ownerDocument = node.ownerDocument;
var ownerWindow = ownerDocument.defaultView;
var boundNode = void 0;
if (bounds === 'parent') {
boundNode = node.parentNode;
} else {
boundNode = ownerDocument.querySelector(bounds);
}
if (!(boundNode instanceof HTMLElement)) {
throw new Error('Bounds selector "' + bounds + '" could not find an element.');
}
var nodeStyle = ownerWindow.getComputedStyle(node);
var boundNodeStyle = ownerWindow.getComputedStyle(boundNode);
// Compute bounds. This is a pain with padding and offsets but this gets it exactly right.
bounds = {
left: -node.offsetLeft + (0, _shims.int)(boundNodeStyle.paddingLeft) + (0, _shims.int)(nodeStyle.marginLeft),
top: -node.offsetTop + (0, _shims.int)(boundNodeStyle.paddingTop) + (0, _shims.int)(nodeStyle.marginTop),
right: (0, _domFns.innerWidth)(boundNode) - (0, _domFns.outerWidth)(node) - node.offsetLeft + (0, _shims.int)(boundNodeStyle.paddingRight) - (0, _shims.int)(nodeStyle.marginRight),
bottom: (0, _domFns.innerHeight)(boundNode) - (0, _domFns.outerHeight)(node) - node.offsetTop + (0, _shims.int)(boundNodeStyle.paddingBottom) - (0, _shims.int)(nodeStyle.marginBottom)
};
}
// Keep x and y below right and bottom limits...
if ((0, _shims.isNum)(bounds.right)) x = Math.min(x, bounds.right);
if ((0, _shims.isNum)(bounds.bottom)) y = Math.min(y, bounds.bottom);
// But above left and top limits.
if ((0, _shims.isNum)(bounds.left)) x = Math.max(x, bounds.left);
if ((0, _shims.isNum)(bounds.top)) y = Math.max(y, bounds.top);
return [x, y];
}
function snapToGrid(grid /*: [number, number]*/, pendingX /*: number*/, pendingY /*: number*/) /*: [number, number]*/ {
var x = Math.round(pendingX / grid[0]) * grid[0];
var y = Math.round(pendingY / grid[1]) * grid[1];
return [x, y];
}
function canDragX(draggable /*: Draggable*/) /*: boolean*/ {
return draggable.props.axis === 'both' || draggable.props.axis === 'x';
}
function canDragY(draggable /*: Draggable*/) /*: boolean*/ {
return draggable.props.axis === 'both' || draggable.props.axis === 'y';
}
// Get {x, y} positions from event.
function getControlPosition(e /*: MouseTouchEvent*/, touchIdentifier /*: ?number*/, draggableCore /*: DraggableCore*/) /*: ?ControlPosition*/ {
var touchObj = typeof touchIdentifier === 'number' ? (0, _domFns.getTouch)(e, touchIdentifier) : null;
if (typeof touchIdentifier === 'number' && !touchObj) return null; // not the right touch
var node = findDOMNode(draggableCore);
// User can provide an offsetParent if desired.
var offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;
return (0, _domFns.offsetXYFromParent)(touchObj || e, offsetParent);
}
// Create an data object exposed by <DraggableCore>'s events
function createCoreData(draggable /*: DraggableCore*/, x /*: number*/, y /*: number*/) /*: DraggableData*/ {
var state = draggable.state;
var isStart = !(0, _shims.isNum)(state.lastX);
var node = findDOMNode(draggable);
if (isStart) {
// If this is our first move, use the x and y as last coords.
return {
node: node,
deltaX: 0, deltaY: 0,
lastX: x, lastY: y,
x: x, y: y
};
} else {
// Otherwise calculate proper values.
return {
node: node,
deltaX: x - state.lastX, deltaY: y - state.lastY,
lastX: state.lastX, lastY: state.lastY,
x: x, y: y
};
}
}
// Create an data exposed by <Draggable>'s events
function createDraggableData(draggable /*: Draggable*/, coreData /*: DraggableData*/) /*: DraggableData*/ {
return {
node: coreData.node,
x: draggable.state.x + coreData.deltaX,
y: draggable.state.y + coreData.deltaY,
deltaX: coreData.deltaX,
deltaY: coreData.deltaY,
lastX: draggable.state.x,
lastY: draggable.state.y
};
}
// A lot faster than stringify/parse
function cloneBounds(bounds /*: Bounds*/) /*: Bounds*/ {
return {
left: bounds.left,
top: bounds.top,
right: bounds.right,
bottom: bounds.bottom
};
}
function findDOMNode(draggable /*: Draggable | DraggableCore*/) /*: HTMLElement*/ {
var node = _reactDom2.default.findDOMNode(draggable);
if (!node) {
throw new Error('<DraggableCore>: Unmounted during event!');
}
// $FlowIgnore we can't assert on HTMLElement due to tests... FIXME
return node;
}
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(6);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(7);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = __webpack_require__(4);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _domFns = __webpack_require__(5);
var _positionFns = __webpack_require__(9);
var _shims = __webpack_require__(0);
var _log = __webpack_require__(11);
var _log2 = _interopRequireDefault(_log);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/*:: import type {EventHandler, MouseTouchEvent} from './utils/types';*/
// Simple abstraction for dragging events names.
/*:: import type {Element as ReactElement} from 'react';*/
var eventsFor = {
touch: {
start: 'touchstart',
move: 'touchmove',
stop: 'touchend'
},
mouse: {
start: 'mousedown',
move: 'mousemove',
stop: 'mouseup'
}
};
// Default to mouse events.
var dragEventFor = eventsFor.mouse;
/*:: type DraggableCoreState = {
dragging: boolean,
lastX: number,
lastY: number,
touchIdentifier: ?number
};*/
/*:: export type DraggableBounds = {
left: number,
right: number,
top: number,
bottom: number,
};*/
/*:: export type DraggableData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number,
};*/
/*:: export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void;*/
/*:: export type ControlPosition = {x: number, y: number};*/
//
// Define <DraggableCore>.
//
// <DraggableCore> is for advanced usage of <Draggable>. It maintains minimal internal state so it can
// work well with libraries that require more control over the element.
//
/*:: export type DraggableCoreProps = {
allowAnyClick: boolean,
cancel: string,
children: ReactElement<any>,
disabled: boolean,
enableUserSelectHack: boolean,
offsetParent: HTMLElement,
grid: [number, number],
handle: string,
onStart: DraggableEventHandler,
onDrag: DraggableEventHandler,
onStop: DraggableEventHandler,
onMouseDown: (e: MouseEvent) => void,
};*/
var DraggableCore = function (_React$Component) {
_inherits(DraggableCore, _React$Component);
function DraggableCore() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, DraggableCore);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = DraggableCore.__proto__ || Object.getPrototypeOf(DraggableCore)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
dragging: false,
// Used while dragging to determine deltas.
lastX: NaN, lastY: NaN,
touchIdentifier: null
}, _this.handleDragStart = function (e) {
// Make it possible to attach event handlers on top of this one.
_this.props.onMouseDown(e);
// Only accept left-clicks.
if (!_this.props.allowAnyClick && typeof e.button === 'number' && e.button !== 0) return false;
// Get nodes. Be sure to grab relative document (could be iframed)
var thisNode = _reactDom2.default.findDOMNode(_this);
if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {
throw new Error('<DraggableCore> not mounted on DragStart!');
}
var ownerDocument = thisNode.ownerDocument;
// Short circuit if handle or cancel prop was provided and selector doesn't match.
if (_this.props.disabled || !(e.target instanceof ownerDocument.defaultView.Node) || _this.props.handle && !(0, _domFns.matchesSelectorAndParentsTo)(e.target, _this.props.handle, thisNode) || _this.props.cancel && (0, _domFns.matchesSelectorAndParentsTo)(e.target, _this.props.cancel, thisNode)) {
return;
}
// Set touch identifier in component state if this is a touch event. This allows us to
// distinguish between individual touches on multitouch screens by identifying which
// touchpoint was set to this element.
var touchIdentifier = (0, _domFns.getTouchIdentifier)(e);
_this.setState({ touchIdentifier: touchIdentifier });
// Get the current drag point from the event. This is used as the offset.
var position = (0, _positionFns.getControlPosition)(e, touchIdentifier, _this);
if (position == null) return; // not possible but satisfies flow
var x = position.x,
y = position.y;
// Create an event object with all the data parents need to make a decision here.
var coreEvent = (0, _positionFns.createCoreData)(_this, x, y);
(0, _log2.default)('DraggableCore: handleDragStart: %j', coreEvent);
// Call event handler. If it returns explicit false, cancel.
(0, _log2.default)('calling', _this.props.onStart);
var shouldUpdate = _this.props.onStart(e, coreEvent);
if (shouldUpdate === false) return;
// Add a style to the body to disable user-select. This prevents text from
// being selected all over the page.
if (_this.props.enableUserSelectHack) (0, _domFns.addUserSelectStyles)(ownerDocument);
// Initiate dragging. Set the current x and y as offsets
// so we know how much we've moved during the drag. This allows us
// to drag elements around even if they have been moved, without issue.
_this.setState({
dragging: true,
lastX: x,
lastY: y
});
// Add events to the document directly so we catch when the user's mouse/touch moves outside of
// this element. We use different events depending on whether or not we have detected that this
// is a touch-capable device.
(0, _domFns.addEvent)(ownerDocument, dragEventFor.move, _this.handleDrag);
(0, _domFns.addEvent)(ownerDocument, dragEventFor.stop, _this.handleDragStop);
}, _this.handleDrag = function (e) {
// Prevent scrolling on mobile devices, like ipad/iphone.
if (e.type === 'touchmove') e.preventDefault();
// Get the current drag point from the event. This is used as the offset.
var position = (0, _positionFns.getControlPosition)(e, _this.state.touchIdentifier, _this);
if (position == null) return;
var x = position.x,
y = position.y;
// Snap to grid if prop has been provided
if (Array.isArray(_this.props.grid)) {
var _deltaX = x - _this.state.lastX,
_deltaY = y - _this.state.lastY;
var _snapToGrid = (0, _positionFns.snapToGrid)(_this.props.grid, _deltaX, _deltaY);
var _snapToGrid2 = _slicedToArray(_snapToGrid, 2);
_deltaX = _snapToGrid2[0];
_deltaY = _snapToGrid2[1];
if (!_deltaX && !_deltaY) return; // skip useless drag
x = _this.state.lastX + _deltaX, y = _this.state.lastY + _deltaY;
}
var coreEvent = (0, _positionFns.createCoreData)(_this, x, y);
(0, _log2.default)('DraggableCore: handleDrag: %j', coreEvent);
// Call event handler. If it returns explicit false, trigger end.
var shouldUpdate = _this.props.onDrag(e, coreEvent);
if (shouldUpdate === false) {
try {
// $FlowIgnore
_this.handleDragStop(new MouseEvent('mouseup'));
} catch (err) {
// Old browsers
var event = ((document.createEvent('MouseEvents') /*: any*/) /*: MouseTouchEvent*/);
// I see why this insanity was deprecated
// $FlowIgnore
event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
_this.handleDragStop(event);
}
return;
}
_this.setState({
lastX: x,
lastY: y
});
}, _this.handleDragStop = function (e) {
if (!_this.state.dragging) return;
var position = (0, _positionFns.getControlPosition)(e, _this.state.touchIdentifier, _this);
if (position == null) return;
var x = position.x,
y = position.y;
var coreEvent = (0, _positionFns.createCoreData)(_this, x, y);
var thisNode = _reactDom2.default.findDOMNode(_this);
if (thisNode) {
// Remove user-select hack
if (_this.props.enableUserSelectHack) (0, _domFns.removeUserSelectStyles)(thisNode.ownerDocument);
}
(0, _log2.default)('DraggableCore: handleDragStop: %j', coreEvent);