ghost-portal/packages/react-hooks/src/usePopupWindow.ts
Jaco 37f44367b4
Rework context usage (& move most to react-hooks) (#8731)
* Rework context usage (& move most to react-hooks)

* Move use{Accounts, Addresses} to use contexts

* Cleanups

* Global alignment renames

* Combine keyring subjects into KeyringCtx

* Cleanups to contexts

* Small adjustment to window size usage

* Popup test via data-testid

* Fix Bounties tests

* Move getStats to correct location

* Adjust ApiStats

* Do add unsubs (although unneeded)
2023-01-09 12:56:38 +02:00

53 lines
1.8 KiB
TypeScript

// Copyright 2017-2023 @polkadot/react-hooks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import React, { useEffect, useMemo, useState } from 'react';
import { HorizontalPosition, VerticalPosition } from '@polkadot/react-components/Popup/types';
import { getPosition } from '@polkadot/react-components/Popup/utils';
import { createNamedHook } from './createNamedHook';
import { useElementPosition } from './useElementPosition';
import { useScroll } from './useScroll';
import { useWindowSize } from './useWindowSize';
interface Coord {
x: number;
y: number;
}
interface Result {
pointerStyle: VerticalPosition;
renderCoords: Coord;
}
const COORD_0: Coord = { x: 0, y: 0 };
function usePopupWindowImpl (windowRef: React.RefObject<HTMLDivElement>, triggerRef: React.RefObject<HTMLDivElement>, position: HorizontalPosition): Result {
const [renderCoords, setRenderCoords] = useState<Coord>(COORD_0);
const [pointerStyle, setPointerStyle] = useState<VerticalPosition>('top');
const windowCoords = useElementPosition(windowRef);
const triggerCoords = useElementPosition(triggerRef);
const scrollY = useScroll();
const windowSize = useWindowSize();
useEffect(() => {
if (windowSize && triggerCoords) {
setPointerStyle((triggerCoords.y > windowSize.height / 2) ? 'top' : 'bottom');
}
}, [triggerCoords, windowSize]);
useEffect(() => {
if (windowCoords && triggerCoords) {
setRenderCoords(getPosition(triggerCoords, position, pointerStyle, windowCoords, scrollY, windowSize));
}
}, [position, scrollY, triggerCoords, pointerStyle, windowCoords, windowSize]);
return useMemo(
() => ({ pointerStyle, renderCoords }),
[renderCoords, pointerStyle]
);
}
export const usePopupWindow = createNamedHook('usePopupWindow', usePopupWindowImpl);