|
| 1 | +import * as React from 'react'; |
| 2 | +import { |
| 3 | + makeStyles, |
| 4 | + shorthands, |
| 5 | + Button, |
| 6 | + Popover, |
| 7 | + PopoverSurface, |
| 8 | + useId, |
| 9 | + useRestoreFocusTarget, |
| 10 | +} from '@fluentui/react-components'; |
| 11 | +import type { PositioningImperativeRef } from '@fluentui/react-components'; |
| 12 | +const useStyles = makeStyles({ |
| 13 | + container: { |
| 14 | + display: 'flex', |
| 15 | + ...shorthands.gap('10px'), |
| 16 | + }, |
| 17 | + |
| 18 | + contentHeader: { |
| 19 | + marginTop: '0', |
| 20 | + }, |
| 21 | +}); |
| 22 | + |
| 23 | +export const WithoutTrigger = () => { |
| 24 | + const [open, setOpen] = React.useState(false); |
| 25 | + const headerId = useId(); |
| 26 | + const buttonRef = React.useRef<HTMLButtonElement>(null); |
| 27 | + const positioningRef = React.useRef<PositioningImperativeRef>(null); |
| 28 | + const styles = useStyles(); |
| 29 | + const restoreFocusTargetAttribute = useRestoreFocusTarget(); |
| 30 | + |
| 31 | + React.useEffect(() => { |
| 32 | + if (buttonRef.current) { |
| 33 | + positioningRef.current?.setTarget(buttonRef.current); |
| 34 | + } |
| 35 | + }, [buttonRef, positioningRef]); |
| 36 | + |
| 37 | + return ( |
| 38 | + <div className={styles.container}> |
| 39 | + <Button {...restoreFocusTargetAttribute} ref={buttonRef} onClick={() => setOpen(s => !s)}> |
| 40 | + Toggle popover |
| 41 | + </Button> |
| 42 | + <Popover onOpenChange={(_, data) => setOpen(data.open)} trapFocus open={open} positioning={{ positioningRef }}> |
| 43 | + <PopoverSurface aria-labelledby={headerId}> |
| 44 | + <div> |
| 45 | + <h3 id={headerId} className={styles.contentHeader}> |
| 46 | + Popover content |
| 47 | + </h3> |
| 48 | + |
| 49 | + <div>This is some popover content</div> |
| 50 | + </div> |
| 51 | + |
| 52 | + <div> |
| 53 | + <Button>Action</Button> |
| 54 | + <Button>Action</Button> |
| 55 | + </div> |
| 56 | + </PopoverSurface> |
| 57 | + </Popover> |
| 58 | + </div> |
| 59 | + ); |
| 60 | +}; |
| 61 | + |
| 62 | +WithoutTrigger.parameters = { |
| 63 | + docs: { |
| 64 | + description: { |
| 65 | + story: [ |
| 66 | + 'When using a `Popover` without a `PopoverTrigger`, it is up to the user to make sure that the focus is restored correctly', |
| 67 | + 'when the popover is closed. This can be done quite easily by using the `useRestoreFocusTarget` hook. The `Popover` already', |
| 68 | + 'uses the `useRestoreFocusSource` hook directly, which will restore focus to the most recently focused target on close.', |
| 69 | + ].join('\n'), |
| 70 | + }, |
| 71 | + }, |
| 72 | +}; |
0 commit comments