resizeObserver.mjs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Utilities
  2. import { onBeforeUnmount, readonly, ref, watch } from 'vue';
  3. import { refElement } from "../util/index.mjs";
  4. import { IN_BROWSER } from "../util/globals.mjs"; // Types
  5. export function useResizeObserver(callback) {
  6. let box = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'content';
  7. const resizeRef = ref();
  8. const contentRect = ref();
  9. if (IN_BROWSER) {
  10. const observer = new ResizeObserver(entries => {
  11. callback?.(entries, observer);
  12. if (!entries.length) return;
  13. if (box === 'content') {
  14. contentRect.value = entries[0].contentRect;
  15. } else {
  16. contentRect.value = entries[0].target.getBoundingClientRect();
  17. }
  18. });
  19. onBeforeUnmount(() => {
  20. observer.disconnect();
  21. });
  22. watch(resizeRef, (newValue, oldValue) => {
  23. if (oldValue) {
  24. observer.unobserve(refElement(oldValue));
  25. contentRect.value = undefined;
  26. }
  27. if (newValue) observer.observe(refElement(newValue));
  28. }, {
  29. flush: 'post'
  30. });
  31. }
  32. return {
  33. resizeRef,
  34. contentRect: readonly(contentRect)
  35. };
  36. }
  37. //# sourceMappingURL=resizeObserver.mjs.map