Skip to content

Commit

Permalink
fix: wrapped element calcation size and position
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <i@innei.in>
  • Loading branch information
Innei committed Sep 4, 2024
1 parent fa7fb07 commit 86a702c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 19 deletions.
3 changes: 1 addition & 2 deletions src/hooks/shared/use-read-percent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ export const useReadPercent = () => {
const readPercent = usePageScrollLocationSelector(
(scrollTop) => {
const winHeight = getViewport().h
const deltaHeight =
scrollTop >= winHeight ? winHeight : (scrollTop / winHeight) * winHeight
const deltaHeight = scrollTop >= winHeight ? winHeight : scrollTop

return (
Math.floor(
Expand Down
44 changes: 27 additions & 17 deletions src/providers/shared/WrappedElementProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,33 +57,43 @@ export const WrappedElementProvider: Component<WrappedElementProviderProps> = ({
children,
className,
...props
}) => {
return (
<ProviderComposer contexts={Providers}>
<ArticleElementResizeObserver />
<Content {...props} className={className}>
{children}
</Content>
</ProviderComposer>
)
}
const ArticleElementResizeObserver = () => {
}) => (
<ProviderComposer contexts={Providers}>
<ElementResizeObserver />
<Content {...props} className={className}>
{children}
</Content>
</ProviderComposer>
)
const ElementResizeObserver = () => {
const setSize = useSetWrappedElementSize()
const setPos = useSetElementPosition()
const $element = useWrappedElement()
useIsomorphicLayoutEffect(() => {
if (!$element) return
const { height, width, x, y } = $element.getBoundingClientRect()
const { height, width, left, top } = $element.getBoundingClientRect()
setSize({ h: height, w: width })
setPos({ x, y })

const pageX = window.scrollX + left
const pageY = window.scrollY + top
setPos({ x: pageX, y: pageY })

const observer = new ResizeObserver((entries) => {
const entry = entries[0]
const { height, width } = entry.contentRect
const { x, y } = entry.target.getBoundingClientRect()

setSize({ h: height, w: width })
setPos({ x, y })
const { height, width } = entry.contentRect
const { left, top } = $element.getBoundingClientRect()
const pageX = window.scrollX + left
const pageY = window.scrollY + top

setSize((size) => {
if (size.h === height && size.w === width) return size
return { h: height, w: width }
})
setPos((pos) => {
if (pos.x === pageX && pos.y === pageY) return pos
return { x: pageX, y: pageY }
})
})
observer.observe($element)
return () => {
Expand Down

0 comments on commit 86a702c

Please sign in to comment.