hooks icon indicating copy to clipboard operation
hooks copied to clipboard

[RFC] useMeasures

Open KMNowak opened this issue 2 years ago • 1 comments

useMeasures

Description

I'd like to introduce quite commonly used in other libraries of that type functionality of gathering target element relative measurement properties. It is similar to useSize, but it differs in the source of truth and returns more target element properties.

  • useSize uses target and returns clientHeight and clientWidth only
  • useMeasures uses contentRect and returns all described below properties

API

// from src/utils/domTarget.ts
type BasicTarget<T extends TargetType = Element> =
  | (() => TargetValue<T>)
  | TargetValue<T>
  | MutableRefObject<TargetValue<T>>;

interface UseMeasuresRes {
    readonly top: number;
    readonly right: number;
    readonly bottom: number;
    readonly left: number;
    readonly x: number;
    readonly y: number;
    readonly height: number;
    readonly width: number;
}

type UseMeasures = (target: BasicTarget) => UseMeasuresRes

DEMO

export default () => {
  const ref = useRef(null); // we can either use Element instead of ref e.g. document.querySelector('body')
  const { height, width, top, left, x, y, right, bottom } = useMeasures(ref);
  return (
    <div ref={ref}>
      <p>Try to scroll or resize the preview window </p>
      <p>x: {x}</p>
      <p>y: {y}</p>
      <p>top: {top}</p>
      <p>right: {right}</p>
      <p>bottom: {bottom}</p>
      <p>left: {left}</p>
      <p>width: {width}</p>
      <p>height: {height}</p>
    </div>
  );
};

Related PRs

I've already opened a PR with this functionality: https://github.com/alibaba/hooks/pull/1874

Detailed spec

Params

Property Description Type Default
target DOM element or ref object Element | () => Element | MutableRefObject<Element> | null -

Result

Property Description Type Default
x View value x of the element number 0
y View value y of the element number 0
top Position top of the element number 0
right Position right of the element number 0
bottom Position bottom of the element number 0
left Position left of the element number 0
width The width of the element number 0
height The height of the element number 0

KMNowak avatar Sep 15 '22 08:09 KMNowak

My suggestion is to extend useSize,,api like:const { width, height, contentRect } = useSize(),rename useSize and API while waiting for v4

crazylxr avatar Sep 20 '22 01:09 crazylxr

repeat: https://github.com/alibaba/hooks/pull/2063

liuyib avatar Mar 11 '23 10:03 liuyib

Covered by: https://github.com/alibaba/hooks/pull/2063

KMNowak avatar May 28 '23 19:05 KMNowak