util.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import contains from '../vc-util/Dom/contains';
  2. import ResizeObserver from 'resize-observer-polyfill';
  3. export function isSamePoint(prev, next) {
  4. if (prev === next) return true;
  5. if (!prev || !next) return false;
  6. if ('pageX' in next && 'pageY' in next) {
  7. return prev.pageX === next.pageX && prev.pageY === next.pageY;
  8. }
  9. if ('clientX' in next && 'clientY' in next) {
  10. return prev.clientX === next.clientX && prev.clientY === next.clientY;
  11. }
  12. return false;
  13. }
  14. export function restoreFocus(activeElement, container) {
  15. // Focus back if is in the container
  16. if (activeElement !== document.activeElement && contains(container, activeElement) && typeof activeElement.focus === 'function') {
  17. activeElement.focus();
  18. }
  19. }
  20. export function monitorResize(element, callback) {
  21. let prevWidth = null;
  22. let prevHeight = null;
  23. function onResize(_ref) {
  24. let [{
  25. target
  26. }] = _ref;
  27. if (!document.documentElement.contains(target)) return;
  28. const {
  29. width,
  30. height
  31. } = target.getBoundingClientRect();
  32. const fixedWidth = Math.floor(width);
  33. const fixedHeight = Math.floor(height);
  34. if (prevWidth !== fixedWidth || prevHeight !== fixedHeight) {
  35. // https://webkit.org/blog/9997/resizeobserver-in-webkit/
  36. Promise.resolve().then(() => {
  37. callback({
  38. width: fixedWidth,
  39. height: fixedHeight
  40. });
  41. });
  42. }
  43. prevWidth = fixedWidth;
  44. prevHeight = fixedHeight;
  45. }
  46. const resizeObserver = new ResizeObserver(onResize);
  47. if (element) {
  48. resizeObserver.observe(element);
  49. }
  50. return () => {
  51. resizeObserver.disconnect();
  52. };
  53. }