GPQAPP

Форк
0
/
popper-utils.js 
1113 строк · 34.7 Кб
1
/**!
2
 * @fileOverview Kickass library to create and place poppers near their reference elements.
3
 * @version 1.16.1
4
 * @license
5
 * Copyright (c) 2016 Federico Zivolo and contributors
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in all
15
 * copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
 * SOFTWARE.
24
 */
25
/**
26
 * Get CSS computed property of the given element
27
 * @method
28
 * @memberof Popper.Utils
29
 * @argument {Eement} element
30
 * @argument {String} property
31
 */
32
function getStyleComputedProperty(element, property) {
33
  if (element.nodeType !== 1) {
34
    return [];
35
  }
36
  // NOTE: 1 DOM access here
37
  var window = element.ownerDocument.defaultView;
38
  var css = window.getComputedStyle(element, null);
39
  return property ? css[property] : css;
40
}
41

42
/**
43
 * Returns the parentNode or the host of the element
44
 * @method
45
 * @memberof Popper.Utils
46
 * @argument {Element} element
47
 * @returns {Element} parent
48
 */
49
function getParentNode(element) {
50
  if (element.nodeName === 'HTML') {
51
    return element;
52
  }
53
  return element.parentNode || element.host;
54
}
55

56
/**
57
 * Returns the scrolling parent of the given element
58
 * @method
59
 * @memberof Popper.Utils
60
 * @argument {Element} element
61
 * @returns {Element} scroll parent
62
 */
63
function getScrollParent(element) {
64
  // Return body, `getScroll` will take care to get the correct `scrollTop` from it
65
  if (!element) {
66
    return document.body;
67
  }
68

69
  switch (element.nodeName) {
70
    case 'HTML':
71
    case 'BODY':
72
      return element.ownerDocument.body;
73
    case '#document':
74
      return element.body;
75
  }
76

77
  // Firefox want us to check `-x` and `-y` variations as well
78

79
  var _getStyleComputedProp = getStyleComputedProperty(element),
80
      overflow = _getStyleComputedProp.overflow,
81
      overflowX = _getStyleComputedProp.overflowX,
82
      overflowY = _getStyleComputedProp.overflowY;
83

84
  if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
85
    return element;
86
  }
87

88
  return getScrollParent(getParentNode(element));
89
}
90

91
/**
92
 * Returns the reference node of the reference object, or the reference object itself.
93
 * @method
94
 * @memberof Popper.Utils
95
 * @param {Element|Object} reference - the reference element (the popper will be relative to this)
96
 * @returns {Element} parent
97
 */
98
function getReferenceNode(reference) {
99
  return reference && reference.referenceNode ? reference.referenceNode : reference;
100
}
101

102
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
103

104
var isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode);
105
var isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent);
106

107
/**
108
 * Determines if the browser is Internet Explorer
109
 * @method
110
 * @memberof Popper.Utils
111
 * @param {Number} version to check
112
 * @returns {Boolean} isIE
113
 */
114
function isIE(version) {
115
  if (version === 11) {
116
    return isIE11;
117
  }
118
  if (version === 10) {
119
    return isIE10;
120
  }
121
  return isIE11 || isIE10;
122
}
123

124
/**
125
 * Returns the offset parent of the given element
126
 * @method
127
 * @memberof Popper.Utils
128
 * @argument {Element} element
129
 * @returns {Element} offset parent
130
 */
131
function getOffsetParent(element) {
132
  if (!element) {
133
    return document.documentElement;
134
  }
135

136
  var noOffsetParent = isIE(10) ? document.body : null;
137

138
  // NOTE: 1 DOM access here
139
  var offsetParent = element.offsetParent || null;
140
  // Skip hidden elements which don't have an offsetParent
141
  while (offsetParent === noOffsetParent && element.nextElementSibling) {
142
    offsetParent = (element = element.nextElementSibling).offsetParent;
143
  }
144

145
  var nodeName = offsetParent && offsetParent.nodeName;
146

147
  if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
148
    return element ? element.ownerDocument.documentElement : document.documentElement;
149
  }
150

151
  // .offsetParent will return the closest TH, TD or TABLE in case
152
  // no offsetParent is present, I hate this job...
153
  if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
154
    return getOffsetParent(offsetParent);
155
  }
156

157
  return offsetParent;
158
}
159

160
function isOffsetContainer(element) {
161
  var nodeName = element.nodeName;
162

163
  if (nodeName === 'BODY') {
164
    return false;
165
  }
166
  return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
167
}
168

169
/**
170
 * Finds the root node (document, shadowDOM root) of the given element
171
 * @method
172
 * @memberof Popper.Utils
173
 * @argument {Element} node
174
 * @returns {Element} root node
175
 */
176
function getRoot(node) {
177
  if (node.parentNode !== null) {
178
    return getRoot(node.parentNode);
179
  }
180

181
  return node;
182
}
183

184
/**
185
 * Finds the offset parent common to the two provided nodes
186
 * @method
187
 * @memberof Popper.Utils
188
 * @argument {Element} element1
189
 * @argument {Element} element2
190
 * @returns {Element} common offset parent
191
 */
192
function findCommonOffsetParent(element1, element2) {
193
  // This check is needed to avoid errors in case one of the elements isn't defined for any reason
194
  if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
195
    return document.documentElement;
196
  }
197

198
  // Here we make sure to give as "start" the element that comes first in the DOM
199
  var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
200
  var start = order ? element1 : element2;
201
  var end = order ? element2 : element1;
202

203
  // Get common ancestor container
204
  var range = document.createRange();
205
  range.setStart(start, 0);
206
  range.setEnd(end, 0);
207
  var commonAncestorContainer = range.commonAncestorContainer;
208

209
  // Both nodes are inside #document
210

211
  if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
212
    if (isOffsetContainer(commonAncestorContainer)) {
213
      return commonAncestorContainer;
214
    }
215

216
    return getOffsetParent(commonAncestorContainer);
217
  }
218

219
  // one of the nodes is inside shadowDOM, find which one
220
  var element1root = getRoot(element1);
221
  if (element1root.host) {
222
    return findCommonOffsetParent(element1root.host, element2);
223
  } else {
224
    return findCommonOffsetParent(element1, getRoot(element2).host);
225
  }
226
}
227

228
/**
229
 * Gets the scroll value of the given element in the given side (top and left)
230
 * @method
231
 * @memberof Popper.Utils
232
 * @argument {Element} element
233
 * @argument {String} side `top` or `left`
234
 * @returns {number} amount of scrolled pixels
235
 */
236
function getScroll(element) {
237
  var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';
238

239
  var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
240
  var nodeName = element.nodeName;
241

242
  if (nodeName === 'BODY' || nodeName === 'HTML') {
243
    var html = element.ownerDocument.documentElement;
244
    var scrollingElement = element.ownerDocument.scrollingElement || html;
245
    return scrollingElement[upperSide];
246
  }
247

248
  return element[upperSide];
249
}
250

251
/*
252
 * Sum or subtract the element scroll values (left and top) from a given rect object
253
 * @method
254
 * @memberof Popper.Utils
255
 * @param {Object} rect - Rect object you want to change
256
 * @param {HTMLElement} element - The element from the function reads the scroll values
257
 * @param {Boolean} subtract - set to true if you want to subtract the scroll values
258
 * @return {Object} rect - The modifier rect object
259
 */
260
function includeScroll(rect, element) {
261
  var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
262

263
  var scrollTop = getScroll(element, 'top');
264
  var scrollLeft = getScroll(element, 'left');
265
  var modifier = subtract ? -1 : 1;
266
  rect.top += scrollTop * modifier;
267
  rect.bottom += scrollTop * modifier;
268
  rect.left += scrollLeft * modifier;
269
  rect.right += scrollLeft * modifier;
270
  return rect;
271
}
272

273
/*
274
 * Helper to detect borders of a given element
275
 * @method
276
 * @memberof Popper.Utils
277
 * @param {CSSStyleDeclaration} styles
278
 * Result of `getStyleComputedProperty` on the given element
279
 * @param {String} axis - `x` or `y`
280
 * @return {number} borders - The borders size of the given axis
281
 */
282

283
function getBordersSize(styles, axis) {
284
  var sideA = axis === 'x' ? 'Left' : 'Top';
285
  var sideB = sideA === 'Left' ? 'Right' : 'Bottom';
286

287
  return parseFloat(styles['border' + sideA + 'Width']) + parseFloat(styles['border' + sideB + 'Width']);
288
}
289

290
function getSize(axis, body, html, computedStyle) {
291
  return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0);
292
}
293

294
function getWindowSizes(document) {
295
  var body = document.body;
296
  var html = document.documentElement;
297
  var computedStyle = isIE(10) && getComputedStyle(html);
298

299
  return {
300
    height: getSize('Height', body, html, computedStyle),
301
    width: getSize('Width', body, html, computedStyle)
302
  };
303
}
304

305
var _extends = Object.assign || function (target) {
306
  for (var i = 1; i < arguments.length; i++) {
307
    var source = arguments[i];
308

309
    for (var key in source) {
310
      if (Object.prototype.hasOwnProperty.call(source, key)) {
311
        target[key] = source[key];
312
      }
313
    }
314
  }
315

316
  return target;
317
};
318

319
/**
320
 * Given element offsets, generate an output similar to getBoundingClientRect
321
 * @method
322
 * @memberof Popper.Utils
323
 * @argument {Object} offsets
324
 * @returns {Object} ClientRect like output
325
 */
326
function getClientRect(offsets) {
327
  return _extends({}, offsets, {
328
    right: offsets.left + offsets.width,
329
    bottom: offsets.top + offsets.height
330
  });
331
}
332

333
/**
334
 * Get bounding client rect of given element
335
 * @method
336
 * @memberof Popper.Utils
337
 * @param {HTMLElement} element
338
 * @return {Object} client rect
339
 */
340
function getBoundingClientRect(element) {
341
  var rect = {};
342

343
  // IE10 10 FIX: Please, don't ask, the element isn't
344
  // considered in DOM in some circumstances...
345
  // This isn't reproducible in IE10 compatibility mode of IE11
346
  try {
347
    if (isIE(10)) {
348
      rect = element.getBoundingClientRect();
349
      var scrollTop = getScroll(element, 'top');
350
      var scrollLeft = getScroll(element, 'left');
351
      rect.top += scrollTop;
352
      rect.left += scrollLeft;
353
      rect.bottom += scrollTop;
354
      rect.right += scrollLeft;
355
    } else {
356
      rect = element.getBoundingClientRect();
357
    }
358
  } catch (e) {}
359

360
  var result = {
361
    left: rect.left,
362
    top: rect.top,
363
    width: rect.right - rect.left,
364
    height: rect.bottom - rect.top
365
  };
366

367
  // subtract scrollbar size from sizes
368
  var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {};
369
  var width = sizes.width || element.clientWidth || result.width;
370
  var height = sizes.height || element.clientHeight || result.height;
371

372
  var horizScrollbar = element.offsetWidth - width;
373
  var vertScrollbar = element.offsetHeight - height;
374

375
  // if an hypothetical scrollbar is detected, we must be sure it's not a `border`
376
  // we make this check conditional for performance reasons
377
  if (horizScrollbar || vertScrollbar) {
378
    var styles = getStyleComputedProperty(element);
379
    horizScrollbar -= getBordersSize(styles, 'x');
380
    vertScrollbar -= getBordersSize(styles, 'y');
381

382
    result.width -= horizScrollbar;
383
    result.height -= vertScrollbar;
384
  }
385

386
  return getClientRect(result);
387
}
388

389
function getOffsetRectRelativeToArbitraryNode(children, parent) {
390
  var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
391

392
  var isIE10 = isIE(10);
393
  var isHTML = parent.nodeName === 'HTML';
394
  var childrenRect = getBoundingClientRect(children);
395
  var parentRect = getBoundingClientRect(parent);
396
  var scrollParent = getScrollParent(children);
397

398
  var styles = getStyleComputedProperty(parent);
399
  var borderTopWidth = parseFloat(styles.borderTopWidth);
400
  var borderLeftWidth = parseFloat(styles.borderLeftWidth);
401

402
  // In cases where the parent is fixed, we must ignore negative scroll in offset calc
403
  if (fixedPosition && isHTML) {
404
    parentRect.top = Math.max(parentRect.top, 0);
405
    parentRect.left = Math.max(parentRect.left, 0);
406
  }
407
  var offsets = getClientRect({
408
    top: childrenRect.top - parentRect.top - borderTopWidth,
409
    left: childrenRect.left - parentRect.left - borderLeftWidth,
410
    width: childrenRect.width,
411
    height: childrenRect.height
412
  });
413
  offsets.marginTop = 0;
414
  offsets.marginLeft = 0;
415

416
  // Subtract margins of documentElement in case it's being used as parent
417
  // we do this only on HTML because it's the only element that behaves
418
  // differently when margins are applied to it. The margins are included in
419
  // the box of the documentElement, in the other cases not.
420
  if (!isIE10 && isHTML) {
421
    var marginTop = parseFloat(styles.marginTop);
422
    var marginLeft = parseFloat(styles.marginLeft);
423

424
    offsets.top -= borderTopWidth - marginTop;
425
    offsets.bottom -= borderTopWidth - marginTop;
426
    offsets.left -= borderLeftWidth - marginLeft;
427
    offsets.right -= borderLeftWidth - marginLeft;
428

429
    // Attach marginTop and marginLeft because in some circumstances we may need them
430
    offsets.marginTop = marginTop;
431
    offsets.marginLeft = marginLeft;
432
  }
433

434
  if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
435
    offsets = includeScroll(offsets, parent);
436
  }
437

438
  return offsets;
439
}
440

441
function getViewportOffsetRectRelativeToArtbitraryNode(element) {
442
  var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
443

444
  var html = element.ownerDocument.documentElement;
445
  var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
446
  var width = Math.max(html.clientWidth, window.innerWidth || 0);
447
  var height = Math.max(html.clientHeight, window.innerHeight || 0);
448

449
  var scrollTop = !excludeScroll ? getScroll(html) : 0;
450
  var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0;
451

452
  var offset = {
453
    top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
454
    left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
455
    width: width,
456
    height: height
457
  };
458

459
  return getClientRect(offset);
460
}
461

462
/**
463
 * Check if the given element is fixed or is inside a fixed parent
464
 * @method
465
 * @memberof Popper.Utils
466
 * @argument {Element} element
467
 * @argument {Element} customContainer
468
 * @returns {Boolean} answer to "isFixed?"
469
 */
470
function isFixed(element) {
471
  var nodeName = element.nodeName;
472
  if (nodeName === 'BODY' || nodeName === 'HTML') {
473
    return false;
474
  }
475
  if (getStyleComputedProperty(element, 'position') === 'fixed') {
476
    return true;
477
  }
478
  var parentNode = getParentNode(element);
479
  if (!parentNode) {
480
    return false;
481
  }
482
  return isFixed(parentNode);
483
}
484

485
/**
486
 * Finds the first parent of an element that has a transformed property defined
487
 * @method
488
 * @memberof Popper.Utils
489
 * @argument {Element} element
490
 * @returns {Element} first transformed parent or documentElement
491
 */
492

493
function getFixedPositionOffsetParent(element) {
494
  // This check is needed to avoid errors in case one of the elements isn't defined for any reason
495
  if (!element || !element.parentElement || isIE()) {
496
    return document.documentElement;
497
  }
498
  var el = element.parentElement;
499
  while (el && getStyleComputedProperty(el, 'transform') === 'none') {
500
    el = el.parentElement;
501
  }
502
  return el || document.documentElement;
503
}
504

505
/**
506
 * Computed the boundaries limits and return them
507
 * @method
508
 * @memberof Popper.Utils
509
 * @param {HTMLElement} popper
510
 * @param {HTMLElement} reference
511
 * @param {number} padding
512
 * @param {HTMLElement} boundariesElement - Element used to define the boundaries
513
 * @param {Boolean} fixedPosition - Is in fixed position mode
514
 * @returns {Object} Coordinates of the boundaries
515
 */
516
function getBoundaries(popper, reference, padding, boundariesElement) {
517
  var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
518

519
  // NOTE: 1 DOM access here
520

521
  var boundaries = { top: 0, left: 0 };
522
  var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
523

524
  // Handle viewport case
525
  if (boundariesElement === 'viewport') {
526
    boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition);
527
  } else {
528
    // Handle other cases based on DOM element used as boundaries
529
    var boundariesNode = void 0;
530
    if (boundariesElement === 'scrollParent') {
531
      boundariesNode = getScrollParent(getParentNode(reference));
532
      if (boundariesNode.nodeName === 'BODY') {
533
        boundariesNode = popper.ownerDocument.documentElement;
534
      }
535
    } else if (boundariesElement === 'window') {
536
      boundariesNode = popper.ownerDocument.documentElement;
537
    } else {
538
      boundariesNode = boundariesElement;
539
    }
540

541
    var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition);
542

543
    // In case of HTML, we need a different computation
544
    if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
545
      var _getWindowSizes = getWindowSizes(popper.ownerDocument),
546
          height = _getWindowSizes.height,
547
          width = _getWindowSizes.width;
548

549
      boundaries.top += offsets.top - offsets.marginTop;
550
      boundaries.bottom = height + offsets.top;
551
      boundaries.left += offsets.left - offsets.marginLeft;
552
      boundaries.right = width + offsets.left;
553
    } else {
554
      // for all the other DOM elements, this one is good
555
      boundaries = offsets;
556
    }
557
  }
558

559
  // Add paddings
560
  padding = padding || 0;
561
  var isPaddingNumber = typeof padding === 'number';
562
  boundaries.left += isPaddingNumber ? padding : padding.left || 0;
563
  boundaries.top += isPaddingNumber ? padding : padding.top || 0;
564
  boundaries.right -= isPaddingNumber ? padding : padding.right || 0;
565
  boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0;
566

567
  return boundaries;
568
}
569

570
function getArea(_ref) {
571
  var width = _ref.width,
572
      height = _ref.height;
573

574
  return width * height;
575
}
576

577
/**
578
 * Utility used to transform the `auto` placement to the placement with more
579
 * available space.
580
 * @method
581
 * @memberof Popper.Utils
582
 * @argument {Object} data - The data object generated by update method
583
 * @argument {Object} options - Modifiers configuration and options
584
 * @returns {Object} The data object, properly modified
585
 */
586
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {
587
  var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
588

589
  if (placement.indexOf('auto') === -1) {
590
    return placement;
591
  }
592

593
  var boundaries = getBoundaries(popper, reference, padding, boundariesElement);
594

595
  var rects = {
596
    top: {
597
      width: boundaries.width,
598
      height: refRect.top - boundaries.top
599
    },
600
    right: {
601
      width: boundaries.right - refRect.right,
602
      height: boundaries.height
603
    },
604
    bottom: {
605
      width: boundaries.width,
606
      height: boundaries.bottom - refRect.bottom
607
    },
608
    left: {
609
      width: refRect.left - boundaries.left,
610
      height: boundaries.height
611
    }
612
  };
613

614
  var sortedAreas = Object.keys(rects).map(function (key) {
615
    return _extends({
616
      key: key
617
    }, rects[key], {
618
      area: getArea(rects[key])
619
    });
620
  }).sort(function (a, b) {
621
    return b.area - a.area;
622
  });
623

624
  var filteredAreas = sortedAreas.filter(function (_ref2) {
625
    var width = _ref2.width,
626
        height = _ref2.height;
627
    return width >= popper.clientWidth && height >= popper.clientHeight;
628
  });
629

630
  var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
631

632
  var variation = placement.split('-')[1];
633

634
  return computedPlacement + (variation ? '-' + variation : '');
635
}
636

637
var timeoutDuration = function () {
638
  var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
639
  for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {
640
    if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
641
      return 1;
642
    }
643
  }
644
  return 0;
645
}();
646

647
function microtaskDebounce(fn) {
648
  var called = false;
649
  return function () {
650
    if (called) {
651
      return;
652
    }
653
    called = true;
654
    window.Promise.resolve().then(function () {
655
      called = false;
656
      fn();
657
    });
658
  };
659
}
660

661
function taskDebounce(fn) {
662
  var scheduled = false;
663
  return function () {
664
    if (!scheduled) {
665
      scheduled = true;
666
      setTimeout(function () {
667
        scheduled = false;
668
        fn();
669
      }, timeoutDuration);
670
    }
671
  };
672
}
673

674
var supportsMicroTasks = isBrowser && window.Promise;
675

676
/**
677
* Create a debounced version of a method, that's asynchronously deferred
678
* but called in the minimum time possible.
679
*
680
* @method
681
* @memberof Popper.Utils
682
* @argument {Function} fn
683
* @returns {Function}
684
*/
685
var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce;
686

687
/**
688
 * Mimics the `find` method of Array
689
 * @method
690
 * @memberof Popper.Utils
691
 * @argument {Array} arr
692
 * @argument prop
693
 * @argument value
694
 * @returns index or -1
695
 */
696
function find(arr, check) {
697
  // use native find if supported
698
  if (Array.prototype.find) {
699
    return arr.find(check);
700
  }
701

702
  // use `filter` to obtain the same behavior of `find`
703
  return arr.filter(check)[0];
704
}
705

706
/**
707
 * Return the index of the matching object
708
 * @method
709
 * @memberof Popper.Utils
710
 * @argument {Array} arr
711
 * @argument prop
712
 * @argument value
713
 * @returns index or -1
714
 */
715
function findIndex(arr, prop, value) {
716
  // use native findIndex if supported
717
  if (Array.prototype.findIndex) {
718
    return arr.findIndex(function (cur) {
719
      return cur[prop] === value;
720
    });
721
  }
722

723
  // use `find` + `indexOf` if `findIndex` isn't supported
724
  var match = find(arr, function (obj) {
725
    return obj[prop] === value;
726
  });
727
  return arr.indexOf(match);
728
}
729

730
/**
731
 * Get the position of the given element, relative to its offset parent
732
 * @method
733
 * @memberof Popper.Utils
734
 * @param {Element} element
735
 * @return {Object} position - Coordinates of the element and its `scrollTop`
736
 */
737
function getOffsetRect(element) {
738
  var elementRect = void 0;
739
  if (element.nodeName === 'HTML') {
740
    var _getWindowSizes = getWindowSizes(element.ownerDocument),
741
        width = _getWindowSizes.width,
742
        height = _getWindowSizes.height;
743

744
    elementRect = {
745
      width: width,
746
      height: height,
747
      left: 0,
748
      top: 0
749
    };
750
  } else {
751
    elementRect = {
752
      width: element.offsetWidth,
753
      height: element.offsetHeight,
754
      left: element.offsetLeft,
755
      top: element.offsetTop
756
    };
757
  }
758

759
  // position
760
  return getClientRect(elementRect);
761
}
762

763
/**
764
 * Get the outer sizes of the given element (offset size + margins)
765
 * @method
766
 * @memberof Popper.Utils
767
 * @argument {Element} element
768
 * @returns {Object} object containing width and height properties
769
 */
770
function getOuterSizes(element) {
771
  var window = element.ownerDocument.defaultView;
772
  var styles = window.getComputedStyle(element);
773
  var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0);
774
  var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0);
775
  var result = {
776
    width: element.offsetWidth + y,
777
    height: element.offsetHeight + x
778
  };
779
  return result;
780
}
781

782
/**
783
 * Get the opposite placement of the given one
784
 * @method
785
 * @memberof Popper.Utils
786
 * @argument {String} placement
787
 * @returns {String} flipped placement
788
 */
789
function getOppositePlacement(placement) {
790
  var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
791
  return placement.replace(/left|right|bottom|top/g, function (matched) {
792
    return hash[matched];
793
  });
794
}
795

796
/**
797
 * Get offsets to the popper
798
 * @method
799
 * @memberof Popper.Utils
800
 * @param {Object} position - CSS position the Popper will get applied
801
 * @param {HTMLElement} popper - the popper element
802
 * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
803
 * @param {String} placement - one of the valid placement options
804
 * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
805
 */
806
function getPopperOffsets(popper, referenceOffsets, placement) {
807
  placement = placement.split('-')[0];
808

809
  // Get popper node sizes
810
  var popperRect = getOuterSizes(popper);
811

812
  // Add position, width and height to our offsets object
813
  var popperOffsets = {
814
    width: popperRect.width,
815
    height: popperRect.height
816
  };
817

818
  // depending by the popper placement we have to compute its offsets slightly differently
819
  var isHoriz = ['right', 'left'].indexOf(placement) !== -1;
820
  var mainSide = isHoriz ? 'top' : 'left';
821
  var secondarySide = isHoriz ? 'left' : 'top';
822
  var measurement = isHoriz ? 'height' : 'width';
823
  var secondaryMeasurement = !isHoriz ? 'height' : 'width';
824

825
  popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
826
  if (placement === secondarySide) {
827
    popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
828
  } else {
829
    popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
830
  }
831

832
  return popperOffsets;
833
}
834

835
/**
836
 * Get offsets to the reference element
837
 * @method
838
 * @memberof Popper.Utils
839
 * @param {Object} state
840
 * @param {Element} popper - the popper element
841
 * @param {Element} reference - the reference element (the popper will be relative to this)
842
 * @param {Element} fixedPosition - is in fixed position mode
843
 * @returns {Object} An object containing the offsets which will be applied to the popper
844
 */
845
function getReferenceOffsets(state, popper, reference) {
846
  var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
847

848
  var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
849
  return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition);
850
}
851

852
/**
853
 * Get the prefixed supported property name
854
 * @method
855
 * @memberof Popper.Utils
856
 * @argument {String} property (camelCase)
857
 * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
858
 */
859
function getSupportedPropertyName(property) {
860
  var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
861
  var upperProp = property.charAt(0).toUpperCase() + property.slice(1);
862

863
  for (var i = 0; i < prefixes.length; i++) {
864
    var prefix = prefixes[i];
865
    var toCheck = prefix ? '' + prefix + upperProp : property;
866
    if (typeof document.body.style[toCheck] !== 'undefined') {
867
      return toCheck;
868
    }
869
  }
870
  return null;
871
}
872

873
/**
874
 * Check if the given variable is a function
875
 * @method
876
 * @memberof Popper.Utils
877
 * @argument {Any} functionToCheck - variable to check
878
 * @returns {Boolean} answer to: is a function?
879
 */
880
function isFunction(functionToCheck) {
881
  var getType = {};
882
  return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
883
}
884

885
/**
886
 * Helper used to know if the given modifier is enabled.
887
 * @method
888
 * @memberof Popper.Utils
889
 * @returns {Boolean}
890
 */
891
function isModifierEnabled(modifiers, modifierName) {
892
  return modifiers.some(function (_ref) {
893
    var name = _ref.name,
894
        enabled = _ref.enabled;
895
    return enabled && name === modifierName;
896
  });
897
}
898

899
/**
900
 * Helper used to know if the given modifier depends from another one.<br />
901
 * It checks if the needed modifier is listed and enabled.
902
 * @method
903
 * @memberof Popper.Utils
904
 * @param {Array} modifiers - list of modifiers
905
 * @param {String} requestingName - name of requesting modifier
906
 * @param {String} requestedName - name of requested modifier
907
 * @returns {Boolean}
908
 */
909
function isModifierRequired(modifiers, requestingName, requestedName) {
910
  var requesting = find(modifiers, function (_ref) {
911
    var name = _ref.name;
912
    return name === requestingName;
913
  });
914

915
  var isRequired = !!requesting && modifiers.some(function (modifier) {
916
    return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
917
  });
918

919
  if (!isRequired) {
920
    var _requesting = '`' + requestingName + '`';
921
    var requested = '`' + requestedName + '`';
922
    console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');
923
  }
924
  return isRequired;
925
}
926

927
/**
928
 * Tells if a given input is a number
929
 * @method
930
 * @memberof Popper.Utils
931
 * @param {*} input to check
932
 * @return {Boolean}
933
 */
934
function isNumeric(n) {
935
  return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
936
}
937

938
/**
939
 * Get the window associated with the element
940
 * @argument {Element} element
941
 * @returns {Window}
942
 */
943
function getWindow(element) {
944
  var ownerDocument = element.ownerDocument;
945
  return ownerDocument ? ownerDocument.defaultView : window;
946
}
947

948
/**
949
 * Remove event listeners used to update the popper position
950
 * @method
951
 * @memberof Popper.Utils
952
 * @private
953
 */
954
function removeEventListeners(reference, state) {
955
  // Remove resize event listener on window
956
  getWindow(reference).removeEventListener('resize', state.updateBound);
957

958
  // Remove scroll event listener on scroll parents
959
  state.scrollParents.forEach(function (target) {
960
    target.removeEventListener('scroll', state.updateBound);
961
  });
962

963
  // Reset state
964
  state.updateBound = null;
965
  state.scrollParents = [];
966
  state.scrollElement = null;
967
  state.eventsEnabled = false;
968
  return state;
969
}
970

971
/**
972
 * Loop trough the list of modifiers and run them in order,
973
 * each of them will then edit the data object.
974
 * @method
975
 * @memberof Popper.Utils
976
 * @param {dataObject} data
977
 * @param {Array} modifiers
978
 * @param {String} ends - Optional modifier name used as stopper
979
 * @returns {dataObject}
980
 */
981
function runModifiers(modifiers, data, ends) {
982
  var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
983

984
  modifiersToRun.forEach(function (modifier) {
985
    if (modifier['function']) {
986
      // eslint-disable-line dot-notation
987
      console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
988
    }
989
    var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
990
    if (modifier.enabled && isFunction(fn)) {
991
      // Add properties to offsets to make them a complete clientRect object
992
      // we do this before each modifier to make sure the previous one doesn't
993
      // mess with these values
994
      data.offsets.popper = getClientRect(data.offsets.popper);
995
      data.offsets.reference = getClientRect(data.offsets.reference);
996

997
      data = fn(data, modifier);
998
    }
999
  });
1000

1001
  return data;
1002
}
1003

1004
/**
1005
 * Set the attributes to the given popper
1006
 * @method
1007
 * @memberof Popper.Utils
1008
 * @argument {Element} element - Element to apply the attributes to
1009
 * @argument {Object} styles
1010
 * Object with a list of properties and values which will be applied to the element
1011
 */
1012
function setAttributes(element, attributes) {
1013
  Object.keys(attributes).forEach(function (prop) {
1014
    var value = attributes[prop];
1015
    if (value !== false) {
1016
      element.setAttribute(prop, attributes[prop]);
1017
    } else {
1018
      element.removeAttribute(prop);
1019
    }
1020
  });
1021
}
1022

1023
/**
1024
 * Set the style to the given popper
1025
 * @method
1026
 * @memberof Popper.Utils
1027
 * @argument {Element} element - Element to apply the style to
1028
 * @argument {Object} styles
1029
 * Object with a list of properties and values which will be applied to the element
1030
 */
1031
function setStyles(element, styles) {
1032
  Object.keys(styles).forEach(function (prop) {
1033
    var unit = '';
1034
    // add unit if the value is numeric and is one of the following
1035
    if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
1036
      unit = 'px';
1037
    }
1038
    element.style[prop] = styles[prop] + unit;
1039
  });
1040
}
1041

1042
function attachToScrollParents(scrollParent, event, callback, scrollParents) {
1043
  var isBody = scrollParent.nodeName === 'BODY';
1044
  var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;
1045
  target.addEventListener(event, callback, { passive: true });
1046

1047
  if (!isBody) {
1048
    attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
1049
  }
1050
  scrollParents.push(target);
1051
}
1052

1053
/**
1054
 * Setup needed event listeners used to update the popper position
1055
 * @method
1056
 * @memberof Popper.Utils
1057
 * @private
1058
 */
1059
function setupEventListeners(reference, options, state, updateBound) {
1060
  // Resize event listener on window
1061
  state.updateBound = updateBound;
1062
  getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });
1063

1064
  // Scroll event listener on scroll parents
1065
  var scrollElement = getScrollParent(reference);
1066
  attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
1067
  state.scrollElement = scrollElement;
1068
  state.eventsEnabled = true;
1069

1070
  return state;
1071
}
1072

1073
// This is here just for backward compatibility with versions lower than v1.10.3
1074
// you should import the utilities using named exports, if you want them all use:
1075
// ```
1076
// import * as PopperUtils from 'popper-utils';
1077
// ```
1078
// The default export will be removed in the next major version.
1079
var index = {
1080
  computeAutoPlacement: computeAutoPlacement,
1081
  debounce: debounce,
1082
  findIndex: findIndex,
1083
  getBordersSize: getBordersSize,
1084
  getBoundaries: getBoundaries,
1085
  getBoundingClientRect: getBoundingClientRect,
1086
  getClientRect: getClientRect,
1087
  getOffsetParent: getOffsetParent,
1088
  getOffsetRect: getOffsetRect,
1089
  getOffsetRectRelativeToArbitraryNode: getOffsetRectRelativeToArbitraryNode,
1090
  getOuterSizes: getOuterSizes,
1091
  getParentNode: getParentNode,
1092
  getPopperOffsets: getPopperOffsets,
1093
  getReferenceOffsets: getReferenceOffsets,
1094
  getScroll: getScroll,
1095
  getScrollParent: getScrollParent,
1096
  getStyleComputedProperty: getStyleComputedProperty,
1097
  getSupportedPropertyName: getSupportedPropertyName,
1098
  getWindowSizes: getWindowSizes,
1099
  isFixed: isFixed,
1100
  isFunction: isFunction,
1101
  isModifierEnabled: isModifierEnabled,
1102
  isModifierRequired: isModifierRequired,
1103
  isNumeric: isNumeric,
1104
  removeEventListeners: removeEventListeners,
1105
  runModifiers: runModifiers,
1106
  setAttributes: setAttributes,
1107
  setStyles: setStyles,
1108
  setupEventListeners: setupEventListeners
1109
};
1110

1111
export { computeAutoPlacement, debounce, findIndex, getBordersSize, getBoundaries, getBoundingClientRect, getClientRect, getOffsetParent, getOffsetRect, getOffsetRectRelativeToArbitraryNode, getOuterSizes, getParentNode, getPopperOffsets, getReferenceOffsets, getScroll, getScrollParent, getStyleComputedProperty, getSupportedPropertyName, getWindowSizes, isFixed, isFunction, isModifierEnabled, isModifierRequired, isNumeric, removeEventListeners, runModifiers, setAttributes, setStyles, setupEventListeners };
1112
export default index;
1113
//# sourceMappingURL=popper-utils.js.map
1114

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.