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

Enhancement/popover location #237

Merged
merged 4 commits into from
Nov 2, 2023
Merged
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
Original file line number Diff line number Diff line change
@@ -1,18 +1,48 @@
import React from 'react';
import React, { useCallback, useLayoutEffect, useRef, useState } from 'react';
import { FocusScope } from 'react-aria';

import { Button } from '../../../button/index.js';
import { CloseIcon } from '../../../icon/index.js';
import { usePopoverPosition } from '../../popover.hooks.js';

import { styles as panelStyles } from './panel.styles.js';
import { type PanelProps } from './panel.types.js';
import { type PanelProps, Position } from './panel.types.js';

export function Panel({ state, heading, headingTag: Tag = 'h1', content, placement = 'top', id }: PanelProps) {
const styles = panelStyles({ placement });
export function Panel({ state, heading, headingTag: Tag = 'h1', content, placement, id, triggerRef }: PanelProps) {
const popoverRef = useRef<HTMLDivElement>(null);
const arrowRef = useRef<HTMLDivElement>(null);
const remSize = parseInt(window.getComputedStyle(document.getElementsByTagName('html')[0]).fontSize);

const [position, setPosition] = useState<Position>({
placement: 'top',
offset: 'left',
panelPosition: triggerRef.current ? triggerRef.current.offsetWidth / 2 / remSize : 0,
arrowPosition: popoverRef.current ? popoverRef.current.getBoundingClientRect().width / 2 / remSize : 0,
});

useLayoutEffect(() => {
setPosition(usePopoverPosition(triggerRef, popoverRef, arrowRef, placement));
}, [state.isOpen]);

const getPopoverClass = useCallback(() => {
return {
[position.offset as string]:
position.offset === 'left' ? `${position.panelPosition}rem` : `-${position.panelPosition}rem`,
transform: position.offset === 'left' ? 'translateX(-50%)' : 'none',
};
}, [position]);

const getArrowClass = useCallback(() => {
return {
[!position.offset || position.offset === 'left' ? 'left' : 'right']: `${position.arrowPosition}rem`,
};
}, [position]);

const styles = panelStyles({ placement: position.placement });

return (
<FocusScope restoreFocus>
<div className={styles.popover()} id={id}>
<div className={styles.popover()} style={getPopoverClass()} id={id} ref={popoverRef}>
<div className={styles.content()}>
<Tag className={styles.heading()}>{heading}</Tag>
<div className={styles.body()}>{content}</div>
Expand All @@ -24,7 +54,7 @@ export function Panel({ state, heading, headingTag: Tag = 'h1', content, placeme
aria-label="Close popover"
/>
</div>
<div aria-hidden className={styles.arrow()} />
<div aria-hidden className={styles.arrow()} style={getArrowClass()} ref={arrowRef} />
</div>
</FocusScope>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ export const styles = tv(
variants: {
placement: {
top: {
popover: 'bottom-full left-1/2 mb-2.5 -translate-x-1/2',
arrow: 'left-1/2 top-full -translate-x-1/2 after:top-[-12px] after:translate-x-[-7px]',
popover: 'bottom-full mb-2.5',
arrow: 'top-full after:top-[-12px] after:translate-x-[-7px]',
},
bottom: {
popover: 'left-1/2 top-full mt-2.5 -translate-x-1/2',
arrow: 'bottom-full left-1/2 -translate-x-1/2 rotate-180 after:bottom-[1px] after:translate-x-[-7px]',
popover: 'top-full mt-2.5',
arrow: 'bottom-full rotate-180 after:bottom-[1px] after:translate-x-[-7px]',
},
},
},
Expand Down
15 changes: 13 additions & 2 deletions packages/ui/src/components/popover/components/panel/panel.types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HTMLAttributes } from 'react';
import { HTMLAttributes, RefObject } from 'react';
import { OverlayTriggerState } from 'react-stately';

export type PanelProps = {
Expand All @@ -15,11 +15,22 @@ export type PanelProps = {
*/
headingTag?: keyof Pick<JSX.IntrinsicElements, 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'>;
/**
* Overlay trigger state
* Placement of popover. If no placement provided it will default to top unless there is no space then will appear on bottom.
*/
placement?: 'top' | 'bottom';
/**
* Overlay trigger state
*/
state: OverlayTriggerState;
/**
* Ref for the trigger
*/
triggerRef: RefObject<HTMLDivElement>;
} & HTMLAttributes<Element>;

export type Position = {
arrowPosition?: number;
offset?: 'left' | 'right';
panelPosition?: number;
placement?: 'top' | 'bottom';
};
15 changes: 13 additions & 2 deletions packages/ui/src/components/popover/popover.component.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import React, { useCallback, useEffect, useId } from 'react';
import React, { useCallback, useEffect, useId, useLayoutEffect, useRef } from 'react';
import { useOverlayTriggerState } from 'react-stately';

import { Button } from '../button/index.js';
Expand All @@ -9,6 +9,11 @@ import { Panel } from './components/panel/panel.component.js';
import { styles as popoverStyles } from './popover.styles.js';
import { type PopoverProps } from './popover.types.js';

/**
* TODO: Revisit this component when react-aria has updated usePopover, see: https://github.com/adobe/react-spectrum/discussions/5341
* This version does not currently use react-aria as it blocked so functionality that was needed to match GEL 3.0
*/

export function Popover({
children,
className,
Expand All @@ -21,9 +26,10 @@ export function Popover({
open = false,
icon,
}: PopoverProps) {
const state = useOverlayTriggerState({ defaultOpen: open });
const state = useOverlayTriggerState({});
const panelId = useId();
const styles = popoverStyles({});
const ref = useRef<HTMLDivElement>(null);

const handleClick = useCallback(() => {
onClick();
Expand All @@ -44,6 +50,9 @@ export function Popover({
};
}, [state.isOpen]);

useLayoutEffect(() => {
if (open) state.setOpen(true);
}, [open]);
return (
<div className={styles.base({ className })}>
<Button
Expand All @@ -52,6 +61,7 @@ export function Popover({
aria-expanded={state.isOpen}
aria-controls={panelId}
onClick={handleClick}
ref={ref}
>
{children}
</Button>
Expand All @@ -63,6 +73,7 @@ export function Popover({
content={content}
state={state}
id={panelId}
triggerRef={ref}
/>
)}
</div>
Expand Down
56 changes: 56 additions & 0 deletions packages/ui/src/components/popover/popover.hooks.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { RefObject } from 'react';

import { Position } from './components/panel/panel.types.js';

export const usePopoverPosition = (
triggerRef: RefObject<HTMLDivElement>,
popoverRef: RefObject<HTMLDivElement>,
arrowRef: RefObject<HTMLDivElement>,
placement?: 'top' | 'bottom',
): Position => {
// bail early without refs
if (!triggerRef.current || !popoverRef.current || !arrowRef.current) {
throw new Error('You must pass valid refs.');
}

const trigger = triggerRef.current.getBoundingClientRect();
const popover = popoverRef.current.getBoundingClientRect();
const arrow = arrowRef.current.getBoundingClientRect();
const remSize = parseInt(window.getComputedStyle(document.getElementsByTagName('html')[0]).fontSize);

const position: Position = {
placement: placement ? placement : 'top',
offset: popover.right >= window.innerWidth ? 'right' : 'left',
panelPosition: trigger.width / 2 / remSize,
arrowPosition: (popover.width / 2 - arrow.width / 2) / remSize,
};
if (typeof window === 'undefined') {
return position;
}

const offLeft = popover.left <= 0;
const offRight = popover.right + remSize >= window.innerWidth;

if (offLeft) {
position.panelPosition = (popover.width - popover.right + trigger.width / 2 + remSize) / remSize;
position.arrowPosition = (trigger.right - trigger.width / 2 - arrow.width / 2 - remSize) / remSize;
}

if (offRight) {
position.panelPosition = (window.innerWidth - trigger.right - remSize) / remSize;
position.arrowPosition =
(window.innerWidth - (trigger.left + trigger.width / 2) - (remSize + arrow.width / 2)) / remSize;
}

if (popover.height > trigger.top) {
position.placement = placement ? placement : 'bottom';
return position;
}

if (popover.bottom > window.innerHeight) {
position.placement = placement ? placement : 'top';
return position;
}

return position;
};
78 changes: 64 additions & 14 deletions packages/ui/src/components/popover/popover.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const meta: Meta<typeof Popover> = {
tags: ['autodocs'],
decorators: [
(Story: StoryFn) => (
<div className="p-29">
<div>
<Story />
</div>
),
Expand All @@ -28,7 +28,7 @@ export default meta;
type Story = StoryObj<typeof meta>;

/**
* > Default usage example
* > Default usage example NOTE: Does not display correctly in story view please check individual story
*/
export const Default: Story = {
args: {
Expand All @@ -37,7 +37,7 @@ export const Default: Story = {
};

/**
* > Using icon as trigger
* > Using icon as trigger NOTE: Does not display correctly in story view please check individual story
*/
export const IconTrigger: Story = {
args: {
Expand All @@ -46,7 +46,7 @@ export const IconTrigger: Story = {
};

/**
* > Default open
* > Default open NOTE: Does not display correctly in story view please check individual story
*/
export const DefaultOpen: Story = {
args: {
Expand All @@ -56,7 +56,7 @@ export const DefaultOpen: Story = {
};

/**
* > No heading
* > No heading NOTE: Does not display correctly in story view please check individual story
*/
export const NoHeading: Story = {
args: {
Expand All @@ -67,15 +67,65 @@ export const NoHeading: Story = {
};

/**
* > Top and bottom popover
* > Auto adjustment NOTE: Does not display correctly in story view please check individual story
*/
export const PopoverPlacement = () => (
<div>
<Popover className="mr-3" heading="Heading" placement="top" content={popoverContent} open>
Top Popover
</Popover>
<Popover placement="bottom" heading="Heading" content={popoverContent} open>
Bottom Popover
export const AutoAdjustment = () => (
<>
<div>
If no placement prop is used the popover will not automatically adjust itself to the top or bottom. It will always
adjust it self if it is too close to either edge of the screen.
</div>
<Popover heading="Heading" content={popoverContent}>
Auto Bottom Popover
</Popover>
</div>
<div className="mt-[200px] flex flex-col">
<div className="flex justify-between">
<Popover heading="Heading" content={popoverContent}>
Left Popover
</Popover>
<Popover heading="Heading" content={popoverContent}>
Center Popover
</Popover>
<Popover heading="Heading" content={popoverContent}>
Right Popover
</Popover>
</div>
</div>
</>
);

/**
* > Top and bottom popover NOTE: Does not display correctly in story view please check individual story
*/
export const PopoverPlacement = () => (
<>
<div>
If the placement prop is used the popover will not automatically adjust itself to the top or bottom but will still
adjust left and right if too close to the edge.
</div>
<div className="mt-[200px] flex flex-col space-y-2">
<div className="flex justify-between">
<Popover placement="top" heading="Heading" content={popoverContent} open>
Left Top Popover
</Popover>
<Popover placement="top" heading="Heading" content={popoverContent} open>
Center Top Popover
</Popover>
<Popover placement="top" heading="Heading" content={popoverContent} open>
Right Top Popover
</Popover>
</div>
<div className="flex justify-between">
<Popover placement="bottom" heading="Heading" content={popoverContent} open>
Left Bottom Popover
</Popover>
<Popover placement="bottom" heading="Heading" content={popoverContent} open>
Center Bottom Popover
</Popover>
<Popover placement="bottom" heading="Heading" content={popoverContent} open>
Right Bottom Popover
</Popover>
</div>
</div>
</>
);
2 changes: 1 addition & 1 deletion packages/ui/src/components/popover/popover.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export type PopoverProps = {
*/
open?: boolean;
/**
* Placement of popover
* Placement of popover. If no placement provided it will default to top unless there is no space then will appear on bottom.
*/
placement?: 'top' | 'bottom';
} & HTMLAttributes<Element> &
Expand Down