Skip to content
Draft
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
100 changes: 100 additions & 0 deletions packages/react/src/AnchoredOverlay/AnchoredOverlay.dev.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import {Button} from '../Button'
import {AnchoredOverlay} from '.'
import {Stack} from '../Stack'
import {Dialog, Spinner, ActionList, ActionMenu} from '..'
import Octicon from '../Octicon'
import Avatar from '../Avatar'
import Link from '../Link'
import {LocationIcon, RepoIcon} from '@primer/octicons-react'
import classes from './AnchoredOverlay.features.stories.module.css'

const meta = {
title: 'Components/AnchoredOverlay/Dev',
Expand All @@ -13,6 +18,34 @@ const meta = {

export default meta

const hoverCard = (
<Stack gap="condensed" style={{padding: '16px'}}>
<Stack direction="horizontal" gap="condensed" justify="space-between">
<Avatar src="https://avatars.githubusercontent.com/u/7143434?v=4" size={48} />
<Button size="small">Follow</Button>
</Stack>
<Stack direction="horizontal" gap="none">
<span className={classes.UserName}>monalisa</span>
<span className={classes.UserMeta}>
<Link inline muted href="#">
Monalisa Octocat
</Link>
</span>
</Stack>
<span className={classes.Bio}>
Former beach cat and champion swimmer. Now your friendly octopus with a normal face.
</span>
<Stack direction="horizontal" gap="none">
<Octicon className={classes.Icon} icon={LocationIcon} />
<span className={classes.MetaMuted}>Interwebs</span>
</Stack>
<Stack direction="horizontal" gap="none">
<Octicon className={classes.Icon} icon={RepoIcon} />
<span className={classes.MetaMuted}>Owns this repository</span>
</Stack>
</Stack>
)

export const RepositionAfterContentGrows = () => {
const [open, setOpen] = useState(false)
const [loading, setLoading] = useState(true)
Expand Down Expand Up @@ -345,3 +378,70 @@ export const ManyOverlays = () => {
</div>
)
}

const gridPositions = [
{row: 'start', col: 'start'},
{row: 'start', col: 'center'},
{row: 'start', col: 'end'},
{row: 'center', col: 'start'},
{row: 'center', col: 'center'},
{row: 'center', col: 'end'},
{row: 'end', col: 'start'},
{row: 'end', col: 'center'},
{row: 'end', col: 'end'},
]

export const AnchorPositionGridFallbackDisabled = () => {
return <AnchorPositionGridFallback cssAnchorPositioningSettings={{fallbackStrategy: 'none'}} />
}

const AnchorPositionGridFallback = ({
cssAnchorPositioningSettings,
}: {
cssAnchorPositioningSettings: {fallbackStrategy: 'none' | 'opposite-side'}
}) => {
const [openCell, setOpenCell] = useState<string | null>(null)

return (
<div className={classes.AnchorGridContainer}>
<div className={classes.AnchorGrid}>
<div className={classes.AnchorGridInner}>
{gridPositions.map(({row, col}) => {
const key = `${row}-${col}`
const isCenter = row === 'center' && col === 'center'

return (
<div key={key} className={classes.AnchorGridCell}>
<span className={classes.AnchorGridLabel}>
{row} / {col}
</span>
{isCenter ? (
<AnchoredOverlay
open={openCell === key}
onOpen={() => setOpenCell(key)}
onClose={() => setOpenCell(null)}
renderAnchor={props => <Button {...props}>Anchor</Button>}
overlayProps={{
role: 'dialog',
'aria-modal': true,
'aria-label': 'Anchor Position Grid Demo',
}}
focusZoneSettings={{disabled: true}}
preventOverflow={false}
cssAnchorPositioningSettings={cssAnchorPositioningSettings}
>
<div className={classes.FlexColFill}>{hoverCard}</div>
</AnchoredOverlay>
) : null}
</div>
)
})}
</div>
</div>
</div>
)
}

export const AnchorPositionGridFallbackOppositeSide = () => {
return <AnchorPositionGridFallback cssAnchorPositioningSettings={{fallbackStrategy: 'opposite-side'}} />
}
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ export const CenteredOnPage = () => {
'aria-modal': true,
'aria-label': 'Centered Overlay Demo',
}}
cssAnchorPositioningSettings={{fallbackStrategy: 'default'}}
focusZoneSettings={{disabled: true}}
preventOverflow={false}
>
Expand Down
66 changes: 66 additions & 0 deletions packages/react/src/AnchoredOverlay/AnchoredOverlay.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,50 @@ describe('AnchoredOverlay feature flag specific behavior', () => {
expect(overlay).not.toHaveAttribute('popover')
})

it('should disable CSS side fallbacks when cssAnchorPositioningSettings.fallbackStrategy is "none"', () => {
const {baseElement} = render(
<FeatureFlags flags={{primer_react_css_anchor_positioning: true}}>
<BaseStyles>
<AnchoredOverlay
open={true}
onOpen={() => {}}
onClose={() => {}}
renderAnchor={props => <Button {...props}>Anchor Button</Button>}
side="outside-bottom"
cssAnchorPositioningSettings={{fallbackStrategy: 'none'}}
>
<button type="button">Focusable Child</button>
</AnchoredOverlay>
</BaseStyles>
</FeatureFlags>,
)

const overlay = baseElement.querySelector('[data-component="AnchoredOverlay"]') as HTMLElement
expect(overlay.style.getPropertyValue('position-try-fallbacks')).toBe('none')
})

it('should only allow opposite-side CSS fallback when cssAnchorPositioningSettings.fallbackStrategy is "opposite-side"', () => {
const {baseElement} = render(
<FeatureFlags flags={{primer_react_css_anchor_positioning: true}}>
<BaseStyles>
<AnchoredOverlay
open={true}
onOpen={() => {}}
onClose={() => {}}
renderAnchor={props => <Button {...props}>Anchor Button</Button>}
side="outside-bottom"
cssAnchorPositioningSettings={{fallbackStrategy: 'opposite-side'}}
>
<button type="button">Focusable Child</button>
</AnchoredOverlay>
</BaseStyles>
</FeatureFlags>,
)

const overlay = baseElement.querySelector('[data-component="AnchoredOverlay"]') as HTMLElement
expect(overlay.style.getPropertyValue('position-try-fallbacks')).toBe('flip-block')
})

describe('when overlayProps.portalContainerName is provided', () => {
it('should fall back to JS positioning (data-anchor-position="false") even with the flag enabled', () => {
const portalRoot = document.createElement('div')
Expand Down Expand Up @@ -504,6 +548,28 @@ describe('AnchoredOverlay feature flag specific behavior', () => {
const overlay = baseElement.querySelector('[data-component="AnchoredOverlay"]')
expect(overlay).not.toHaveAttribute('popover')
})

it('should ignore cssAnchorPositioningSettings when CSS anchor positioning is disabled', () => {
const {baseElement} = render(
<FeatureFlags flags={{primer_react_css_anchor_positioning: false}}>
<BaseStyles>
<AnchoredOverlay
open={true}
onOpen={() => {}}
onClose={() => {}}
renderAnchor={props => <Button {...props}>Anchor Button</Button>}
side="outside-bottom"
cssAnchorPositioningSettings={{fallbackStrategy: 'none'}}
>
<button type="button">Focusable Child</button>
</AnchoredOverlay>
</BaseStyles>
</FeatureFlags>,
)

const overlay = baseElement.querySelector('[data-component="AnchoredOverlay"]') as HTMLElement
expect(overlay.style.getPropertyValue('position-try-fallbacks')).toBe('')
})
})
})

Expand Down
63 changes: 62 additions & 1 deletion packages/react/src/AnchoredOverlay/AnchoredOverlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,18 @@ interface AnchoredOverlayBaseProps extends Pick<OverlayProps, 'height' | 'width'
* and the browser supports native CSS anchor positioning. Has no effect otherwise. Defaults to `"portal"`.
*/
renderAs?: 'portal' | 'popover'

/**
* Settings for CSS anchor positioning behavior when CSS anchor positioning is active.
*
* `fallbackStrategy` controls CSS fallback behavior:
* - `"default"`: use built-in CSS fallback rules.
* - `"none"`: keep the requested side with no CSS fallbacks.
* - `"opposite-side"`: only allow fallback to the opposite side.
*
* Ignored when CSS anchor positioning is not active.
*/
cssAnchorPositioningSettings?: {fallbackStrategy: 'default' | 'none' | 'opposite-side'}
}

export type AnchoredOverlayProps = AnchoredOverlayBaseProps &
Expand Down Expand Up @@ -167,6 +179,7 @@ export const AnchoredOverlay: React.FC<React.PropsWithChildren<AnchoredOverlayPr
displayCloseButton = true,
closeButtonProps = defaultCloseButtonProps,
renderAs = 'portal',
cssAnchorPositioningSettings,
}) => {
const cssAnchorPositioningFlag = useFeatureFlag('primer_react_css_anchor_positioning')
// Lazy initial state so feature detection runs once per mount on the client.
Expand Down Expand Up @@ -301,6 +314,17 @@ export const AnchoredOverlay: React.FC<React.PropsWithChildren<AnchoredOverlayPr
if (open && currentOverlay) {
currentOverlay.style.setProperty('position-anchor', resolvedAnchorName)

const positionTryFallbacks = getCSSAnchorPositionTryFallbacks(
side,
cssAnchorPositioningSettings?.fallbackStrategy ?? 'default',
)

if (positionTryFallbacks) {
currentOverlay.style.setProperty('position-try-fallbacks', positionTryFallbacks)
} else {
currentOverlay.style.removeProperty('position-try-fallbacks')
}

// Defer the getBoundingClientRect read into a `requestAnimationFrame` so the style write above
// does not force a synchronous layout.
pendingPositionFrame = requestAnimationFrame(() => {
Expand Down Expand Up @@ -344,11 +368,22 @@ export const AnchoredOverlay: React.FC<React.PropsWithChildren<AnchoredOverlayPr
// The overlay may no longer be in the DOM at this point, so we need to check for its presence before trying to update it.
if (currentOverlay) {
currentOverlay.style.removeProperty('position-anchor')
currentOverlay.style.removeProperty('position-try-fallbacks')
}
}
// overlayRef is a stable ref object; including it in deps is unnecessary.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cssAnchorPositioning, shouldRenderAsPopover, open, anchorElement, overlayElement, id, width])
}, [
cssAnchorPositioning,
shouldRenderAsPopover,
open,
anchorElement,
overlayElement,
id,
width,
side,
cssAnchorPositioningSettings,
])

const showXIcon = onClose && variant.narrow === 'fullscreen' && displayCloseButton
const XButtonAriaLabelledBy = closeButtonProps['aria-labelledby']
Expand Down Expand Up @@ -474,6 +509,32 @@ function getDefaultPosition(
return {horizontal, leftOffset, rightOffset, suggestedSide}
}

function getCSSAnchorPositionTryFallbacks(
side: PositionSettings['side'],
strategy: 'default' | 'none' | 'opposite-side',
): string | undefined {
// Disable all CSS fallbacks (including those defined in the stylesheet).
if (strategy === 'none') return 'none'

// Restrict fallbacks to flipping to the opposite side along the relevant axis.
if (strategy === 'opposite-side') {
switch (side) {
case 'outside-top':
case 'outside-bottom':
return 'flip-block'
case 'outside-left':
case 'outside-right':
return 'flip-inline'
default:
return undefined
}
}

// 'default': don't write an inline `position-try-fallbacks`, so the
// stylesheet-defined fallback list on `.AnchoredOverlay` takes effect.
return undefined
}

function assignRef<T>(
ref: React.MutableRefObject<T | null> | ((instance: T | null) => void) | null | undefined,
value: T | null,
Expand Down
Loading