Skip to content

Commit

Permalink
fix(fuselage, fuselage-hooks): Position (#1045)
Browse files Browse the repository at this point in the history
Co-authored-by: Douglas Fabris <devfabris@gmail.com>
  • Loading branch information
ggazzo and dougfabris committed May 9, 2023
1 parent 279bc86 commit 9ba3fac
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
15 changes: 9 additions & 6 deletions packages/fuselage-hooks/src/usePosition/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import type { RefObject, CSSProperties } from 'react';

import { useDebouncedCallback } from '../useDebouncedCallback';
Expand Down Expand Up @@ -171,7 +171,7 @@ export function getPositionStyle({
} as UsePositionResult;
}

const UPDATE_DEBOUNCE_DELAY = 10;
const UPDATE_DEBOUNCE_DELAY = 30;

/**
* Hook to deal and position an element using an anchor
Expand All @@ -192,6 +192,12 @@ export function usePosition<TTarget extends Element, TAnchor extends Element>(
): UsePositionResult {
const [style, setStyle] = useSafely(useState<UsePositionResult>(emptyStyle));

const containerRef = useRef(container);

useEffect(() => {
containerRef.current = container;
}, [container]);

const handleBoundingClientRectChange = useDebouncedCallback(
useMutableCallback(() => {
const target = targetRef.current;
Expand Down Expand Up @@ -238,9 +244,6 @@ export function usePosition<TTarget extends Element, TAnchor extends Element>(

useBoundingClientRectChanges(targetRef, handleBoundingClientRectChange);
useBoundingClientRectChanges(anchorRef, handleBoundingClientRectChange);
useBoundingClientRectChanges(
{ current: container },
handleBoundingClientRectChange
);
useBoundingClientRectChanges(containerRef, handleBoundingClientRectChange);
return style;
}
11 changes: 10 additions & 1 deletion packages/fuselage/src/components/Position/Position.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
ReactPortal,
ReactElement,
} from 'react';
import { useRef, useMemo, cloneElement, useState } from 'react';
import { useRef, useMemo, cloneElement, useState, useEffect } from 'react';
import { createPortal } from 'react-dom';

import type Box from '../Box';
Expand Down Expand Up @@ -51,6 +51,15 @@ const Position = ({
return element;
});

useEffect(
() => () => {
if (portalContainer.childNodes.length === 0) {
document.body.removeChild(portalContainer);
}
},
[portalContainer]
);

return createPortal(
cloneElement(children, {
ref: target,
Expand Down

0 comments on commit 9ba3fac

Please sign in to comment.