Skip to content

Commit

Permalink
perf: run only position engine when active / needed
Browse files Browse the repository at this point in the history
  • Loading branch information
abelflopes committed Jul 4, 2024
1 parent a5642a8 commit bf3861c
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 7 deletions.
1 change: 1 addition & 0 deletions packages/components/_provisional/src/dropdown/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export const Dropdown = ({
}: Readonly<DropdownProps>): React.ReactNode =>
open && (
<PositionEngine
active={open}
exclude={excludeAutoPosition}
position={position}
anchorRef={anchorRef}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect, useState, type default as React } from "react";
import * as PositionEngineCore from "./position-engine-core";

export interface PositionEngineProps {
active: boolean;
position: PositionEngineCore.PositionEngineOptions["position"];
exclude?: PositionEngineCore.PositionEngineOptions["exclude"];
anchorRef: React.RefObject<HTMLElement>;
Expand All @@ -11,6 +12,7 @@ export interface PositionEngineProps {
}

export const PositionEngine = ({
active,
anchorRef,
render,
position,
Expand All @@ -19,7 +21,7 @@ export const PositionEngine = ({
const [renderedElement, setRenderedElement] = useState<React.ReactNode>();

useEffect(() => {
if (!anchorRef.current) return;
if (!anchorRef.current || !active) return;

const positionEngine = new PositionEngineCore.PositionEngine({
position,
Expand All @@ -31,7 +33,7 @@ export const PositionEngine = ({
});

return positionEngine.destroy;
}, [anchorRef, position, render, exclude]);
}, [anchorRef, position, render, exclude, active]);

return renderedElement;
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable max-lines -- ddd */
import { type StandardLonghandProperties } from "csstype";

type PositionEngineBasePosition = "top" | "bottom" | "left" | "right";
Expand Down Expand Up @@ -50,8 +49,7 @@ export class PositionEngine {
}

public init = (): void => {
this.render();

this.throttledRender();
this.resizeObserver.observe(this.options.element);
window.addEventListener("resize", this.throttledRender);
window.addEventListener("scroll", this.throttledRender, { capture: true });
Expand All @@ -60,7 +58,7 @@ export class PositionEngine {
public destroy = (): void => {
this.resizeObserver.disconnect();
window.removeEventListener("resize", this.throttledRender);
window.removeEventListener("scroll", this.throttledRender);
window.removeEventListener("scroll", this.throttledRender, { capture: true });

if (this.animationFrame !== undefined) cancelAnimationFrame(this.animationFrame);
};
Expand Down Expand Up @@ -296,4 +294,3 @@ export class PositionEngine {
});
};
}
/* eslint-enable max-lines */

0 comments on commit bf3861c

Please sign in to comment.