geist-org / geist-ui

A design system for building modern websites and applications.
https://geist-ui.dev
MIT License
4.34k stars 334 forks source link

The position calculated by the getRectFromDOMWithContainer method needs to be subtracted from the offset of the body #833

Closed shervinchen closed 5 months ago

shervinchen commented 1 year ago

Bug report 🐞

Version & Environment

Expected Behaviour

The position calculated by the getRectFromDOMWithContainer method needs to be subtracted from the offset of the body

Actual results (or Errors)

If body or root element is offset(for example: body or root element has a margin), getRectFromDOMWithContainer can’t get the right position

I think the correct implementation should be:

const getRectFromDOMWithContainer = (
  domRect?: DOMRect,
  getContainer?: () => HTMLElement | null,
): ReactiveDomReact => {
  if (!domRect) return defaultRect
  const bodyRect = document.body.getBoundingClientRect()
  const container = getContainer ? getContainer() : null
  const { top: offsetTop, left: offsetLeft } = getElementOffset(container)

  return {
    ...domRect,
    width: domRect.width || domRect.right - domRect.left,
    height: domRect.height || domRect.top - domRect.bottom,
    top: container ? domRect.bottom + container.scrollTop - offsetTop : domRect.bottom - bodyRect.top,
    left: container ? domRect.left + container.scrollLeft - offsetLeft : domRect.left - bodyRect.left,
    elementTop: container ? domRect.top - container.top - offsetTop : domRect.top - bodyRect.top,
  }
}