util.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.isSamePoint = isSamePoint;
  7. exports.monitorResize = monitorResize;
  8. exports.restoreFocus = restoreFocus;
  9. var _contains = _interopRequireDefault(require("../vc-util/Dom/contains"));
  10. var _resizeObserverPolyfill = _interopRequireDefault(require("resize-observer-polyfill"));
  11. function isSamePoint(prev, next) {
  12. if (prev === next) return true;
  13. if (!prev || !next) return false;
  14. if ('pageX' in next && 'pageY' in next) {
  15. return prev.pageX === next.pageX && prev.pageY === next.pageY;
  16. }
  17. if ('clientX' in next && 'clientY' in next) {
  18. return prev.clientX === next.clientX && prev.clientY === next.clientY;
  19. }
  20. return false;
  21. }
  22. function restoreFocus(activeElement, container) {
  23. // Focus back if is in the container
  24. if (activeElement !== document.activeElement && (0, _contains.default)(container, activeElement) && typeof activeElement.focus === 'function') {
  25. activeElement.focus();
  26. }
  27. }
  28. function monitorResize(element, callback) {
  29. let prevWidth = null;
  30. let prevHeight = null;
  31. function onResize(_ref) {
  32. let [{
  33. target
  34. }] = _ref;
  35. if (!document.documentElement.contains(target)) return;
  36. const {
  37. width,
  38. height
  39. } = target.getBoundingClientRect();
  40. const fixedWidth = Math.floor(width);
  41. const fixedHeight = Math.floor(height);
  42. if (prevWidth !== fixedWidth || prevHeight !== fixedHeight) {
  43. // https://webkit.org/blog/9997/resizeobserver-in-webkit/
  44. Promise.resolve().then(() => {
  45. callback({
  46. width: fixedWidth,
  47. height: fixedHeight
  48. });
  49. });
  50. }
  51. prevWidth = fixedWidth;
  52. prevHeight = fixedHeight;
  53. }
  54. const resizeObserver = new _resizeObserverPolyfill.default(onResize);
  55. if (element) {
  56. resizeObserver.observe(element);
  57. }
  58. return () => {
  59. resizeObserver.disconnect();
  60. };
  61. }