Skip to content
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
54 changes: 54 additions & 0 deletions src/react/components/ui/anchored-surface.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { renderToString } from "react-dom/server";
import { assert, assertEquals, assertStringIncludes } from "#veryfront/testing/assert";
import { describe, it } from "#veryfront/testing/bdd";
import { Popover, PopoverTrigger } from "./popover.tsx";
import { DropdownMenu, DropdownMenuTrigger } from "./dropdown-menu.tsx";

describe("anchored surfaces anchor to the trigger ref", () => {
it("Popover root renders no wrapper node", () => {
const html = renderToString(
<Popover>
<PopoverTrigger>Open</PopoverTrigger>
</Popover>,
);

// The trigger button is the outermost markup - no anchor <span> wrapper.
assert(
html.startsWith("<button"),
`expected trigger-first markup, got: ${html.slice(0, 60)}`,
);
assertEquals(html.includes("relative inline-block"), false);
assertStringIncludes(html, 'aria-haspopup="dialog"');
});

it("DropdownMenu root renders no wrapper node", () => {
const html = renderToString(
<DropdownMenu>
<DropdownMenuTrigger>Open</DropdownMenuTrigger>
</DropdownMenu>,
);

assert(
html.startsWith("<button"),
`expected trigger-first markup, got: ${html.slice(0, 60)}`,
);
assertEquals(html.includes("relative inline-block"), false);
assertStringIncludes(html, 'aria-haspopup="menu"');
});

it("asChild trigger keeps the child as the outermost node", () => {
const html = renderToString(
<Popover>
<PopoverTrigger asChild>
<a href="#open">Open</a>
</PopoverTrigger>
</Popover>,
);

assert(
html.startsWith("<a "),
`expected the slotted child as outermost markup, got: ${html.slice(0, 60)}`,
);
assertStringIncludes(html, 'aria-haspopup="dialog"');
});
});
32 changes: 22 additions & 10 deletions src/react/components/ui/anchored-surface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/
import * as React from "react";
import { cx as cn } from "./cva.ts";
import { Slot } from "./slot.tsx";
import { composeRefs, Slot } from "./slot.tsx";
import { Floating } from "./floating.tsx";
import { type DisclosureOptions, useDisclosure } from "./disclosure.ts";

Expand All @@ -21,6 +21,8 @@ export interface AnchoredState {
/** Props for `AnchoredTrigger` (returned by the factory). */
export interface AnchoredTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
asChild?: boolean;
/** Composed with the internal positioning-anchor ref. */
ref?: React.Ref<HTMLButtonElement>;
/** `aria-haspopup` value -- `"dialog"` for Popover, `"menu"` for DropdownMenu. */
haspopup: NonNullable<React.AriaAttributes["aria-haspopup"]>;
}
Expand All @@ -44,8 +46,9 @@ export function createAnchoredSurfaceParts() {
const Context = React.createContext<AnchoredState | null>(null);

/**
* Anchor `<span>` + disclosure state + context provider.
* The span is the positioning anchor for `Floating`.
* Disclosure state + context provider. Renders no node of its own - the
* positioning anchor for `Floating` is the trigger element itself, carried
* on context as `anchorRef` and attached by `AnchoredTrigger`.
*/
function AnchoredRoot(
{ children, open, defaultOpen, onOpenChange }: DisclosureOptions & {
Expand All @@ -56,20 +59,25 @@ export function createAnchoredSurfaceParts() {
const anchorRef = React.useRef<HTMLElement | null>(null);
const ctx = React.useMemo(() => ({ open: isOpen, setOpen, anchorRef }), [isOpen, setOpen]);
return (
<span ref={anchorRef} className="relative inline-block">
<Context.Provider value={ctx}>
{children}
</Context.Provider>
</span>
<Context.Provider value={ctx}>
{children}
</Context.Provider>
);
}

/**
* Toggle trigger. Sets `aria-haspopup` and `aria-expanded`; toggles open on
* click. Skins differ only in the `haspopup` value they supply.
* click; carries the positioning-anchor ref (composed with any consumer
* `ref`, including through `asChild`). Skins differ only in the `haspopup`
* value they supply.
*
* `asChild` contract: the child must forward `ref` to its DOM node (every
* `ui` component does; refs pass as regular props on function components in
* React 19). A child that drops `ref` leaves the surface unanchored —
* `Floating` warns in that case instead of silently rendering nothing.
*/
function AnchoredTrigger(
{ children, asChild, onClick, haspopup, ...props }: AnchoredTriggerProps,
{ children, asChild, onClick, haspopup, ref, ...props }: AnchoredTriggerProps,
): React.ReactElement {
Comment thread
kojiwakayama marked this conversation as resolved.
const ctx = React.useContext(Context);
const Comp = asChild ? Slot : "button";
Expand All @@ -78,6 +86,10 @@ export function createAnchoredSurfaceParts() {
{...(asChild ? {} : { type: "button" as const })}
aria-haspopup={haspopup}
aria-expanded={ctx?.open}
ref={composeRefs<HTMLButtonElement>(
ctx?.anchorRef as React.Ref<HTMLButtonElement> | undefined,
ref,
)}
Comment thread
kojiwakayama marked this conversation as resolved.
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
onClick?.(e);
// Guard ctx before reading ctx.open (trigger may render outside a Root).
Expand Down
10 changes: 8 additions & 2 deletions src/react/components/ui/dropdown-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,15 @@ export function DropdownMenu(props: DropdownMenuProps): React.ReactElement {
return <_Root {...props} />;
}

/** Trigger — toggles the menu. `asChild` merges onto the child element. */
/**
* Trigger — toggles the menu; the positioning anchor. `asChild` merges onto
* the child element, which must forward `ref` to its DOM node.
*/
export function DropdownMenuTrigger(
props: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean },
props: React.ButtonHTMLAttributes<HTMLButtonElement> & {
asChild?: boolean;
ref?: React.Ref<HTMLButtonElement>;
},
): React.ReactElement {
return <_Trigger {...props} haspopup="menu" />;
}
Expand Down
12 changes: 11 additions & 1 deletion src/react/components/ui/floating.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ import * as React from "react";
import { createPortal } from "react-dom";
import { UI_SCOPE_SELECTOR } from "./design-tokens.ts";

// Warn once per session, not per render, when a surface opens unanchored.
let warnedMissingAnchor = false;

/** Props accepted by `<Floating>`. */
export interface FloatingProps extends React.HTMLAttributes<HTMLDivElement> {
/** Element the surface is positioned against (usually the trigger wrapper). */
/** Element the surface is positioned against (usually the trigger element). */
anchorRef: React.RefObject<HTMLElement | null>;
open: boolean;
/** Horizontal edge to align to. */
Expand Down Expand Up @@ -57,6 +60,13 @@ export function Floating({
React.useLayoutEffect(() => {
if (!open) return;
const update = () => {
if (anchorRef.current === null && !warnedMissingAnchor) {
warnedMissingAnchor = true;
console.warn(
"[ui] Floating surface opened without an anchor element. " +
"If the trigger uses asChild, its child must forward `ref` to a DOM node.",
);
}
const a = anchorRef.current?.getBoundingClientRect();
const c = ref.current;
if (!a || !c) return;
Expand Down
10 changes: 8 additions & 2 deletions src/react/components/ui/popover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,15 @@ export function Popover(props: PopoverProps): React.ReactElement {
return <_Root {...props} />;
}

/** Trigger — toggles the popover. `asChild` merges onto the child element. */
/**
* Trigger — toggles the popover; the positioning anchor. `asChild` merges onto
* the child element, which must forward `ref` to its DOM node.
*/
export function PopoverTrigger(
props: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean },
props: React.ButtonHTMLAttributes<HTMLButtonElement> & {
asChild?: boolean;
ref?: React.Ref<HTMLButtonElement>;
},
): React.ReactElement {
return <_Trigger {...props} haspopup="dialog" />;
}
Expand Down
2 changes: 1 addition & 1 deletion src/react/components/ui/slot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import * as React from "react";
type AnyProps = Record<string, unknown>;

/** Compose multiple refs into one callback ref. */
function composeRefs<T>(
export function composeRefs<T>(
...refs: Array<React.Ref<T> | undefined>
): React.RefCallback<T> {
return (node) => {
Expand Down