Skip to content

Commit

Permalink
feat(fuselage-hooks): usePosition listening to components size chan…
Browse files Browse the repository at this point in the history
…ges (#782)

* wip: resize observer

* Listen to element size changes

* Add observer mock to tests

* fix one more test
  • Loading branch information
gabriellsh authored Jul 19, 2022
1 parent 583f759 commit 79fdb3e
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/fuselage-hooks/src/usePosition.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { withResizeObserverMock } from 'testing-utils/mocks/withResizeObserverMock';

import {
getPositionStyle,
getTargetBoundaries,
getVariantBoundaries,
} from './usePosition';
// TODO: add tests targeting the hook itself

withResizeObserverMock();

const container = {
bottom: 1000,
height: 1000,
Expand Down
8 changes: 8 additions & 0 deletions packages/fuselage-hooks/src/usePosition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
};
Expand Down
3 changes: 3 additions & 0 deletions packages/fuselage/src/components/Menu/Menu.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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]', () => {
Expand Down

0 comments on commit 79fdb3e

Please sign in to comment.