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

Position hover card above or below anchor if right and left don't work #1097

Merged
merged 2 commits into from
Dec 13, 2024
Merged
Changes from 1 commit
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
31 changes: 22 additions & 9 deletions src/components/hover-cards.vue
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,25 @@ const component = shallowRef(null);
const placement = ref(undefined);

const popoverRef = ref(null);
const positionPopover = () => {
const rightOfAnchor = hoverCard.anchor.getBoundingClientRect().right;
const componentElement = popoverRef.value.$el.children[0];
const componentWidth = componentElement.getBoundingClientRect().width;
// Subtracting 50 in order to provide some buffer.
const overflowsRight = rightOfAnchor + componentWidth >
document.documentElement.clientWidth - 50;
placement.value = overflowsRight ? 'left' : 'right';
// The minimum distance in px between the edge of the hover card and the edge of
// the viewport. This provides space for the popover arrow, as well some extra
// buffer.
const buffer = 20;
const computePlacement = () => {
const anchorRect = hoverCard.anchor.getBoundingClientRect();
const popoverRect = popoverRef.value.$el.getBoundingClientRect();

// Try 'right' and 'left' first unless the anchor is so close to the bottom
// that the popover won't fit.
if (window.scrollY + anchorRect.bottom + (popoverRect.height / 2) <
matthew-white marked this conversation as resolved.
Show resolved Hide resolved
document.body.scrollHeight) {
if (anchorRect.right + popoverRect.width <=
document.documentElement.clientWidth - buffer)
return 'right';
if (anchorRect.left - popoverRect.width >= buffer) return 'left';
}

return anchorRect.top - popoverRect.height >= buffer ? 'top' : 'bottom';
};
const show = () => {
const typeConfig = types[hoverCard.type];
Expand All @@ -109,7 +120,9 @@ const show = () => {
component.value = typeConfig.component;
// Wait a tick in order to render the component. We need to measure the
// component's width before deciding where to place it.
return nextTick().then(positionPopover);
return nextTick()
.then(computePlacement)
.then(result => { placement.value = result; });
})
// If some but not all requests succeeded, we want to avoid holding onto the
// resources that were successful.
Expand Down