Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | 7x 7x 300x 300x 4x 296x 148x 148x 148x 148x 148x 148x 148x 148x 48x 48x 148x 120x 11x 11x 11x 1x 45x 45x 148x 2x 2x 148x 120x 148x 151x 151x 40x 40x 2x 2x 1x 1x 7x 7x 151x 151x 120x 45x 45x 45x 45x 151x 49x 8x 1x 1x 17x 17x 8x 9x 9x 5x | import * as React from "react";
import { cn } from "../../lib/utils";
/**
* Popover — a non-modal panel anchored to its trigger.
*
* The job-book use is a filter pane or a date picker hanging off a dense
* 32px control: a printed card with a hairline edge, square-ish corners and
* the elevated ground, not a floating cloud.
*
* ACCESSIBILITY CONTRACT (ARIA APG, non-modal dialog)
* - trigger: `aria-haspopup="dialog"`, `aria-expanded`, and `aria-controls`
* pointing at the panel while it is open (and omitted while it is not, so
* the attribute never references a missing id)
* - panel: `role="dialog"` with an accessible name from `label`
* - open moves focus to the first focusable thing in the panel, or to the
* panel itself when it holds none
* - `Escape` closes and returns focus to the trigger
* - Tab out of the panel closes it — a non-modal popover does not trap
* focus, it dismisses when focus leaves
* - a pointer press anywhere outside closes it
*
* Controlled (`open` + `onOpenChange`) or uncontrolled (`defaultOpen`).
*/
const FOCUSABLE_SELECTOR = [
"a[href]",
"button:not([disabled])",
"input:not([disabled]):not([type='hidden'])",
"select:not([disabled])",
"textarea:not([disabled])",
"[tabindex]:not([tabindex='-1'])",
].join(",");
interface PopoverContextValue {
open: boolean;
setOpen: (open: boolean) => void;
panelId: string;
triggerRef: React.RefObject<HTMLButtonElement | null>;
panelRef: React.RefObject<HTMLDivElement | null>;
/** Close, and hand focus back to the trigger. */
dismiss: () => void;
}
const PopoverContext = React.createContext<PopoverContextValue | null>(null);
function usePopoverContext(component: string): PopoverContextValue {
const context = React.useContext(PopoverContext);
if (!context) {
throw new Error(`${component} must be used within Popover`);
}
return context;
}
interface PopoverProps {
children: React.ReactNode;
/** Controlled open state. Omit for an uncontrolled popover. */
open?: boolean;
/** Initial open state when uncontrolled. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
}
export function Popover({
children,
open: openProp,
defaultOpen = false,
onOpenChange,
className,
}: PopoverProps) {
const panelId = React.useId();
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen);
const triggerRef = React.useRef<HTMLButtonElement | null>(null);
const panelRef = React.useRef<HTMLDivElement | null>(null);
const rootRef = React.useRef<HTMLDivElement | null>(null);
const isControlled = openProp !== undefined;
const open = isControlled ? openProp : uncontrolledOpen;
const setOpen = React.useCallback(
(next: boolean) => {
if (!isControlled) setUncontrolledOpen(next);
onOpenChange?.(next);
},
[isControlled, onOpenChange],
);
// A pointer press outside the popover dismisses it. `pointerdown` rather
// than `click` so a press that starts outside closes before the control it
// landed on reacts to it.
React.useEffect(() => {
if (!open) return;
function handlePointerDown(event: PointerEvent) {
const root = rootRef.current;
Iif (!root) return;
if (event.target instanceof Node && root.contains(event.target)) return;
setOpen(false);
}
document.addEventListener("pointerdown", handlePointerDown);
return () => document.removeEventListener("pointerdown", handlePointerDown);
}, [open, setOpen]);
const dismiss = React.useCallback(() => {
setOpen(false);
triggerRef.current?.focus();
}, [setOpen]);
const context = React.useMemo(
() => ({ open, setOpen, panelId, triggerRef, panelRef, dismiss }),
[open, setOpen, panelId, dismiss],
);
// The root is a positioning box and nothing else: every handler lives on
// the trigger or the panel, both of which carry a role.
return (
<PopoverContext.Provider value={context}>
<div ref={rootRef} className={cn("relative inline-block", className)}>
{children}
</div>
</PopoverContext.Provider>
);
}
interface PopoverTriggerProps
extends Omit<
React.ButtonHTMLAttributes<HTMLButtonElement>,
"aria-expanded" | "aria-haspopup" | "aria-controls"
> {
children: React.ReactNode;
}
export function PopoverTrigger({
children,
className,
onClick,
onKeyDown,
...props
}: PopoverTriggerProps) {
const { open, setOpen, panelId, triggerRef, dismiss } =
usePopoverContext("PopoverTrigger");
return (
<button
{...props}
ref={triggerRef}
type="button"
aria-haspopup="dialog"
aria-expanded={open}
aria-controls={open ? panelId : undefined}
onClick={(event) => {
onClick?.(event);
setOpen(!open);
}}
onKeyDown={(event) => {
onKeyDown?.(event);
// Escape on the trigger, for the case where focus came back to
// it with the panel still open.
if (event.key !== "Escape" || !open) return;
event.stopPropagation();
dismiss();
}}
className={cn(
"inline-flex h-10 items-center justify-center gap-2 rounded-md border border-border-default bg-background-elevated px-3 text-sm font-medium text-foreground-default transition-colors hover:bg-background-muted hover:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{children}
</button>
);
}
interface PopoverContentProps {
children: React.ReactNode;
/** Accessible name for the panel. */
label: string;
/** Which edge of the trigger the panel hangs from. */
side?: "bottom" | "top";
/** Which end of the trigger it lines up with. */
align?: "start" | "end" | "center";
className?: string;
}
const sideClasses: Record<NonNullable<PopoverContentProps["side"]>, string> = {
bottom: "top-full mt-1",
top: "bottom-full mb-1",
};
const alignClasses: Record<
NonNullable<PopoverContentProps["align"]>,
string
> = {
start: "left-0",
end: "right-0",
center: "left-1/2 -translate-x-1/2",
};
export function PopoverContent({
children,
label,
side = "bottom",
align = "start",
className,
}: PopoverContentProps) {
const { open, setOpen, panelId, panelRef, triggerRef, dismiss } =
usePopoverContext("PopoverContent");
// Focus in on open. Focus goes back to the trigger from the Escape handler
// and from the trigger's own click, so there is no restore on close here:
// a Tab-out must be allowed to continue outwards.
React.useEffect(() => {
if (!open) return;
const panel = panelRef.current;
Iif (!panel) return;
const first = panel.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);
(first ?? panel).focus();
}, [open, panelRef]);
if (!open) return null;
return (
<div
ref={panelRef}
role="dialog"
aria-label={label}
id={panelId}
tabIndex={-1}
onKeyDown={(event) => {
if (event.key !== "Escape") return;
event.stopPropagation();
dismiss();
}}
onBlur={(event) => {
const next = event.relatedTarget;
// Focus still inside the panel: nothing to do.
if (next instanceof Node && event.currentTarget.contains(next)) {
return;
}
// `relatedTarget` is null when focus falls to the document
// body, which is what a press on a non-focusable area does.
// The outside-pointerdown listener already covers that, and
// acting here too would close the panel the instant a
// non-focusable child is clicked.
Iif (next === null) return;
// Focus moving to the TRIGGER is not a dismissal. Two cases
// land here and both want the panel left alone:
// - Shift+Tab out of the panel's first control, which the
// pattern lets return to the trigger with the panel up
// - a click on the trigger to close, where mousedown focuses
// it before the click fires. Closing here would unmount
// the panel, and the click would then re-open it — the
// trigger would stop being able to close its own popover.
if (next === triggerRef.current) return;
// Otherwise a non-modal popover dismisses when focus leaves
// it, rather than trapping. No refocus: focus has already gone
// where the user sent it.
setOpen(false);
}}
className={cn(
"absolute z-50 min-w-48 rounded-md border border-border-default bg-background-elevated p-3 text-sm text-foreground-default shadow-lg outline-none",
sideClasses[side],
alignClasses[align],
className,
)}
>
{children}
</div>
);
}
|