Use bounding rects for filtering top rect

This commit is contained in:
Jackson Harper
2023-03-10 17:25:09 +08:00
parent 8cf0a6ecb2
commit 5c69b5d8c0
2 changed files with 16 additions and 12 deletions

View File

@ -2,7 +2,6 @@ import { Box } from '../../elements/LayoutPrimitives'
import {
getTopOmnivoreAnchorElement,
parseDomTree,
useReadingProgressAnchor,
} from '../../../lib/hooks/useReadingProgressAnchor'
import {
ScrollOffsetChangeset,
@ -46,6 +45,7 @@ export function Article(props: ArticleProps): JSX.Element {
if (!articleContentRef.current) return
if (!window.document.scrollingElement) return
const anchor = getTopOmnivoreAnchorElement(articleContentRef.current)
console.log(' -- getTopOmnivoreAnchorElement: ', anchor)
const topPositionPercent =
window.scrollY / window.document.scrollingElement.scrollHeight
const anchorIndex = Number(anchor)
@ -106,6 +106,7 @@ export function Article(props: ArticleProps): JSX.Element {
return
}
console.log('props.initialAnchorIndex: ', props.initialAnchorIndex)
const anchorElement = props.highlightHref.current
? document.querySelector(
`[omnivore-highlight-id="${props.highlightHref.current}"]`

View File

@ -11,27 +11,30 @@ const ANCHOR_ELEMENTS_BLOCKED_ATTRIBUTES = [
export const getTopOmnivoreAnchorElement = (
articleContentElement: HTMLElement
): string | undefined => {
let lastVisibleAnchor: Element | undefined = undefined
let topVisibleRect: Element | undefined = undefined
const anchors = Array.from(
document.querySelectorAll(`[data-omnivore-anchor-idx]`)
).reverse()
for (const anchor of anchors) {
const rect = anchor.getBoundingClientRect()
if (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= articleContentElement.clientHeight
) {
lastVisibleAnchor = anchor
} else if (lastVisibleAnchor) {
break
if (rect.top >= 0 && rect.bottom <= articleContentElement.clientHeight) {
if (
topVisibleRect &&
topVisibleRect.getBoundingClientRect().top < rect.top
) {
continue
}
topVisibleRect = anchor
}
}
return (
lastVisibleAnchor?.getAttribute(`data-omnivore-anchor-idx`) ?? undefined
console.log(
' top visible rect:',
topVisibleRect?.getBoundingClientRect().top,
topVisibleRect?.getAttribute(`data-omnivore-anchor-idx`)
)
return topVisibleRect?.getAttribute(`data-omnivore-anchor-idx`) ?? undefined
}
export const useReadingProgressAnchor = (