From 79fdb3e57e20ee63bb059ef18845737b7dad7c7e Mon Sep 17 00:00:00 2001 From: gabriellsh <40830821+gabriellsh@users.noreply.github.com> Date: Tue, 19 Jul 2022 20:45:22 -0300 Subject: [PATCH] feat(fuselage-hooks): `usePosition` listening to components size changes (#782) * wip: resize observer * Listen to element size changes * Add observer mock to tests * fix one more test --- packages/fuselage-hooks/src/usePosition.spec.ts | 4 ++++ packages/fuselage-hooks/src/usePosition.ts | 8 ++++++++ packages/fuselage/src/components/Menu/Menu.spec.tsx | 3 +++ 3 files changed, 15 insertions(+) diff --git a/packages/fuselage-hooks/src/usePosition.spec.ts b/packages/fuselage-hooks/src/usePosition.spec.ts index fb72b3b315..1b6fe630b5 100644 --- a/packages/fuselage-hooks/src/usePosition.spec.ts +++ b/packages/fuselage-hooks/src/usePosition.spec.ts @@ -1,3 +1,5 @@ +import { withResizeObserverMock } from 'testing-utils/mocks/withResizeObserverMock'; + import { getPositionStyle, getTargetBoundaries, @@ -5,6 +7,8 @@ import { } from './usePosition'; // TODO: add tests targeting the hook itself +withResizeObserverMock(); + const container = { bottom: 1000, height: 1000, diff --git a/packages/fuselage-hooks/src/usePosition.ts b/packages/fuselage-hooks/src/usePosition.ts index 3e7b3cc77a..c296221653 100644 --- a/packages/fuselage-hooks/src/usePosition.ts +++ b/packages/fuselage-hooks/src/usePosition.ts @@ -140,10 +140,18 @@ const useBoundingClientRect = ( const parents = getScrollParents(element.current); const passive = { passive: true }; + const observer = new ResizeObserver(() => { + if (!element.current) { + return; + } + callback(); + }); + observer.observe(element.current); window.addEventListener('resize', callback); parents.forEach((el) => el.addEventListener('scroll', callback, passive)); return () => { + observer.disconnect(); window.removeEventListener('resize', callback); parents.forEach((el) => el.removeEventListener('scroll', callback)); }; diff --git a/packages/fuselage/src/components/Menu/Menu.spec.tsx b/packages/fuselage/src/components/Menu/Menu.spec.tsx index a36e7da67d..11c67f9156 100644 --- a/packages/fuselage/src/components/Menu/Menu.spec.tsx +++ b/packages/fuselage/src/components/Menu/Menu.spec.tsx @@ -2,9 +2,12 @@ import { composeStories } from '@storybook/testing-react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; +import { withResizeObserverMock } from 'testing-utils/mocks/withResizeObserverMock'; import * as stories from './Menu.stories'; +withResizeObserverMock(); + const { Simple } = composeStories(stories); describe('[Menu Component]', () => {