Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(use-position): handles scrolling within divs; sticky #1351

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions packages/palette/src/elements/Dropdown/Dropdown.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,37 @@ export const FilterExample = () => {
</Dropdown>
)
}

export const StickyExample = () => {
return (
<div style={{ height: "100vh", overflow: "scroll" }}>
<div style={{ height: "10vh" }} />
<div style={{ position: "sticky", top: 0, zIndex: 1 }}>
<Dropdown
dropdown={
<Box p={1}>
<Text variant="xs">Example content</Text>
</Box>
}
placement="bottom-start"
openDropdownByClick
>
{({ anchorRef, anchorProps }) => {
return (
<Pill
ref={anchorRef as any}
Icon={ChevronSmallDownIcon}
iconPosition="right"
{...anchorProps}
>
Example
</Pill>
)
}}
</Dropdown>
</div>

<div style={{ height: "200vh" }} />
</div>
)
}
52 changes: 52 additions & 0 deletions packages/palette/src/elements/Popover/Popover.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Flex } from "../Flex"
import { Spacer } from "../Spacer"
import { Text } from "../Text"
import { Popover, PopoverProps } from "./Popover"
import { Pill } from "../Pill"

const CONTENT =
"Lorem ipsum dolor sit amet consectetur adipisicing elit. Modi eius autem aliquid cumque, mollitia incidunt totam. Id ut quae hic in quisquam, cupiditate iure nobis, provident minus voluptatem tenetur consequatur."
Expand Down Expand Up @@ -143,6 +144,57 @@ Placement.story = {
parameters: { chromatic: { disable: true } },
}

const ExamplePopover: React.FC = ({ children }) => {
return (
<Popover
popover={
<>
<Text variant="xs" fontWeight="bold">
New filters
</Text>
<Text variant="xs">
Choose artist and alert criteria to accurately narrow your results.
</Text>
</>
}
width={250}
variant="defaultDark"
pointer
visible
ignoreClickOutside
manageFocus={false}
>
{({ anchorRef }) => {
return (
<Box ref={anchorRef as any} m="auto">
{children}
</Box>
)
}}
</Popover>
)
}

export const InternalScrollContainer = () => {
return (
<Box overflow="auto" height="100%">
<Box height="300vh" border="1px dotted" borderColor="black60" p={2}>
<Spacer y={12} />

<Box textAlign="center">
<ExamplePopover>
<Pill>Popover should remain anchored to this element</Pill>
</ExamplePopover>
</Box>
</Box>
</Box>
)
}

InternalScrollContainer.story = {
parameters: { chromatic: { disable: true } },
}

export const ManageFocus = () => {
return (
<States<Partial<PopoverProps>>
Expand Down
9 changes: 1 addition & 8 deletions packages/palette/src/utils/__tests__/usePosition.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,12 @@ describe("placeTooltip", () => {
style: {},
} as HTMLElement

const boundaryRect = {
top: 0,
right: 500,
bottom: 600,
left: 0,
} as DOMRect

placeTooltip({
anchor,
tooltip,
position: "top",
offset: 0,
boundaryRect,
scrollableParents: [],
})

expect(tooltip.style.display).toEqual("block")
Expand Down
188 changes: 144 additions & 44 deletions packages/palette/src/utils/usePosition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,19 @@ export const usePosition = ({
const { current: tooltip } = tooltipRef
const { current: anchor } = anchorRef

setState(placeTooltip({ anchor, tooltip, position, offset, flip, clamp }))
const scrollableParents = getScrollableParents(anchor)

setState(
placeTooltip({
anchor,
tooltip,
position,
offset,
flip,
clamp,
scrollableParents,
})
)
}

// Re-position when there's any change to the tooltip
Expand All @@ -90,25 +102,56 @@ export const usePosition = ({
tooltip.style.top = "0"
tooltip.style.left = "0"

const handleScroll = () => {
setState(placeTooltip({ anchor, tooltip, position, offset, flip, clamp }))
const handle = () => {
setState(
placeTooltip({
anchor,
tooltip,
position,
offset,
flip,
clamp,
scrollableParents,
})
)
}

document.addEventListener("scroll", handleScroll, {
passive: true,
const scrollableParents = getScrollableParents(anchor)
const handlers = scrollableParents.map((scrollableParent) => {
return {
scrollableParent,
handlerScroll: () => {
setState(
placeTooltip({
anchor,
tooltip,
position,
offset,
flip,
clamp,
scrollableParents,
})
)
},
}
})

const handleResize = () => {
setState(placeTooltip({ anchor, tooltip, position, offset, flip, clamp }))
}
handlers.forEach(({ scrollableParent, handlerScroll }) => {
scrollableParent.addEventListener("scroll", handlerScroll, {
passive: true,
})
})

window.addEventListener("resize", handleResize, { passive: true })
window.addEventListener("resize", handle, { passive: true })

setState(placeTooltip({ anchor, tooltip, position, offset, flip, clamp }))
// Initialize
handle()

return () => {
document.removeEventListener("scroll", handleScroll)
window.removeEventListener("resize", handleResize)
window.removeEventListener("resize", handle)
handlers.forEach(({ scrollableParent, handlerScroll }) => {
scrollableParent.removeEventListener("scroll", handlerScroll)
})
}
}, [active, tooltipRef, anchorRef, position])

Expand All @@ -126,19 +169,19 @@ interface PlaceTooltip {
tooltip: HTMLElement
position: Position
offset?: number
boundaryRect?: DOMRect
flip?: boolean
clamp?: boolean
scrollableParents: Array<HTMLElement | Document>
}

export const placeTooltip = ({
anchor,
tooltip,
position,
offset = 0,
boundaryRect = getDocumentBoundingRect(),
flip = true,
clamp = true,
scrollableParents,
}: PlaceTooltip) => {
const elementRect = anchor.getBoundingClientRect()
const tooltipRect = tooltip.getBoundingClientRect()
Expand All @@ -148,11 +191,13 @@ export const placeTooltip = ({
// Flip to avoid edges
const isFlipped =
flip &&
shouldFlip({
targetPosition,
position,
boundaryRect,
tooltipRect,
scrollableParents.some((scrollableParent) => {
return shouldFlip({
targetPosition,
position,
boundaryRect: getBoundingRect(scrollableParent),
tooltipRect,
})
})

if (isFlipped) {
Expand All @@ -162,20 +207,32 @@ export const placeTooltip = ({

// Clamp position within boundary
if (clamp) {
targetPosition.x = Math.max(boundaryRect.left, targetPosition.x)
targetPosition.x = Math.min(
boundaryRect.right - tooltipRect.width,
targetPosition.x
)
targetPosition.y = Math.max(boundaryRect.top, targetPosition.y)
targetPosition.y = Math.min(
boundaryRect.bottom - tooltipRect.height,
targetPosition.y
)
scrollableParents.forEach((scrollableParent) => {
const boundaryRect = getBoundingRect(scrollableParent)

targetPosition.x = Math.max(boundaryRect.left, targetPosition.x)
targetPosition.x = Math.min(
boundaryRect.right - tooltipRect.width,
targetPosition.x
)
targetPosition.y = Math.max(boundaryRect.top, targetPosition.y)
targetPosition.y = Math.min(
boundaryRect.bottom - tooltipRect.height,
targetPosition.y
)
})
}

// Should hide entirely if it scrolls out of view
const shouldHide = !isWithin(elementRect, boundaryRect)
let shouldHide = false
for (const scrollableParent of scrollableParents) {
const boundaryRect = getBoundingRect(scrollableParent)
if (!isWithin(elementRect, boundaryRect)) {
shouldHide = true
break
}
}

tooltip.style.display = shouldHide ? "none" : "block"

tooltip.style.transform = translateWithOffset(
Expand Down Expand Up @@ -323,20 +380,6 @@ const getOppositePosition = (position: Position) => {
}
}

export const getDocumentBoundingRect = () => {
const width = document.body.clientWidth
const height = document.body.clientHeight

return {
top: 0,
left: 0,
right: width,
bottom: height,
width,
height,
} as DOMRect
}

interface ShouldFlip {
targetPosition: TargetPosition
position: Position
Expand Down Expand Up @@ -378,3 +421,60 @@ const isWithin = (elementRect: DOMRect, boundaryRect: DOMRect) => {
boundaryRect.right > elementRect.left
)
}

const getScrollableParents = (element: HTMLElement) => {
let parent = element.parentElement
const scrollableParents: Array<HTMLElement | Document> = []

while (parent) {
const computedStyle = getComputedStyle(parent)
if (
isOverflowSet(computedStyle.overflow) ||
isOverflowSet(computedStyle.overflowY) ||
isOverflowSet(computedStyle.overflowX)
) {
scrollableParents.push(parent)
}
parent = parent.parentElement
}

scrollableParents.push(document)

return scrollableParents
}

const isOverflowSet = (overflowValue: string) => {
return (
overflowValue === "auto" ||
overflowValue === "hidden" ||
overflowValue === "scroll" ||
overflowValue === "overlay"
)
}

const isDocument = (element: HTMLElement | Document): element is Document => {
return element.ownerDocument === null
}

export const getDocumentBoundingRect = () => {
const width = document.body.clientWidth
const height = document.body.clientHeight

return {
top: 0,
left: 0,
right: width,
bottom: height,
width,
height,
x: 0,
y: 0,
toJSON: () => null,
}
}

export const getBoundingRect = (element: HTMLElement | Document): DOMRect => {
return isDocument(element)
? getDocumentBoundingRect()
: element.getBoundingClientRect()
}