From 61317d0a45aaf9a817d0343d52e931801d250af9 Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Sat, 28 Nov 2026 13:06:16 +0100 Subject: [PATCH 1/3] feat(kit): share one hover card and move it between triggers Hover cards on a page share one surface. Moving the pointer to another trigger while a card is open, or within 400ms of it closing, slides the card to the new trigger and resizes it to the new content in 200ms instead of closing one card and popping another. Keyboard moves swap in place; reduced motion keeps only the content fade. HoverCardGroup gives a set of triggers their own surface, and shared={false} gives one card its own. The input tracker also records pointerover, so an overlay opened from pointerenter sees that pointer. Co-Authored-By: Claude Opus 5.5 --- .changeset/hover-card-shared-surface.md | 11 + .../docs/(kit)/components/hover-card.mdx | 46 +- apps/docs/content/docs/design/patterns.mdx | 2 +- apps/docs/export-manifest.json | 8 +- .../docs-demos/src/demos/hover-card/group.tsx | 50 ++ .../src/demos/hover-card/shared.tsx | 39 ++ packages/docs-demos/src/props/hover-card.ts | 22 +- packages/kit/DESIGN.md | 2 +- packages/kit/api/kit.api.md | 135 +++++- .../src/components/HoverCard/HoverCard.tsx | 346 ++++++++------ .../components/HoverCard/HoverCardHost.tsx | 451 ++++++++++++++++++ .../kit/src/components/HoverCard/safe-area.ts | 16 + packages/kit/src/utils/open-source.ts | 3 + packages/kit/test/hover-card-shared.test.tsx | 196 ++++++++ packages/kit/test/hover-card.test.tsx | 11 +- .../src/stories/HoverCard.stories.tsx | 64 +++ 16 files changed, 1240 insertions(+), 162 deletions(-) create mode 100644 .changeset/hover-card-shared-surface.md create mode 100644 packages/docs-demos/src/demos/hover-card/group.tsx create mode 100644 packages/docs-demos/src/demos/hover-card/shared.tsx create mode 100644 packages/kit/src/components/HoverCard/HoverCardHost.tsx create mode 100644 packages/kit/src/components/HoverCard/safe-area.ts create mode 100644 packages/kit/test/hover-card-shared.test.tsx diff --git a/.changeset/hover-card-shared-surface.md b/.changeset/hover-card-shared-surface.md new file mode 100644 index 00000000..a69f97a9 --- /dev/null +++ b/.changeset/hover-card-shared-surface.md @@ -0,0 +1,11 @@ +--- +"@codeui/kit": minor +--- + +Hover cards share one card and move it between triggers. + +- All the hover cards of a page share one card. Moving the pointer or keyboard focus to another trigger while a card is open moves that card at once: it slides to the new trigger, resizes to the new content, and fades the new content in. For 400ms after a card closes, the next one opens at once and without the pop. The move lasts 200ms (`--cui-motion-duration-panel`) with the kit's ease-out. While the pointer is on its way to the open card, another trigger it crosses takes the card only after 150ms of rest. A move from the keyboard swaps the content in place with no motion; with reduced motion only the new content fades in. +- `HoverCardGroup` gives the cards inside it a card of their own, with `skipDelayDuration` for the skip window. `shared={false}` gives one `HoverCard` its own surface; `forceMount` implies it. +- `HoverCardContent` is no longer polymorphic. Its `class`, `classes`, `style`, `ref`, `mount` and dismiss handlers go on the card; other attributes and event handlers go on a `display: contents` element around the children. +- `HoverCard` drops the Kobalte root options it never used (`id`). The trigger renders without a Kobalte popover anchor and still sets `data-expanded` and `data-closed`. +- Overlays opened by hover tell pointer from keyboard more reliably: the input tracker also records `pointerover`, which the browser fires before the `pointermove` that crosses into an element. diff --git a/apps/docs/content/docs/(kit)/components/hover-card.mdx b/apps/docs/content/docs/(kit)/components/hover-card.mdx index b0232b76..738ba061 100644 --- a/apps/docs/content/docs/(kit)/components/hover-card.mdx +++ b/apps/docs/content/docs/(kit)/components/hover-card.mdx @@ -27,9 +27,10 @@ Put `HoverCardTrigger` and `HoverCardContent` in `HoverCard`. Hover the link, or | Export | Renders | `classes` key | `data-cui` | Role | | --- | --- | --- | --- | --- | +| `HoverCardGroup` | Nothing. Gives the cards inside it a surface of their own, optional | none | none | none | | `HoverCard` | Nothing. Holds the open state and the timers | none | none | none | | `HoverCardTrigger` | `a`, or the element passed to `as` | none | `hovercard-trigger` | Link | -| `HoverCardContent` | `div` in a portal on `mount`, or `document.body` | `content` | `hovercard-content` | none | +| `HoverCardContent` | The shared card, a `div` in a portal on `mount` or `document.body`, and a `display: contents` `div` around the children | `content` | `hovercard-content` | none | | `HoverCardList` | `ul`, optional | none | `hovercard-list` | List | | `HoverCardItem` | `li`, with an icon slot, an identifier and a title | `item`, `itemIcon`, `itemId`, `itemTitle` | `hovercard-item`, `hovercard-item-icon`, `hovercard-item-id`, `hovercard-item-title` | List item | @@ -49,6 +50,32 @@ Put `HoverCardTrigger` and `HoverCardContent` in `HoverCard`. Hover the link, or The card opens 500ms after the pointer enters or the trigger gets focus, and closes 150ms after the pointer leaves the trigger and the card. Change this with `openDelay` and `closeDelay`. On its way from the trigger to the card, the pointer may cross the gap between them without closing the card. `ignoreSafeArea` turns that off. +Once one card is open, the next one opens at once. See [Moving between cards](#moving-between-cards). + +### Moving between cards + + + +All the hover cards of a page share one card. When the pointer or keyboard focus moves to another trigger while a card is open, that card moves to the new trigger instead of closing while a second one opens: it slides to its new place, grows or shrinks to the new content, and the new content fades in. Each `HoverCard` keeps its own props, so the card takes the `placement`, `gutter`, class and handlers of the trigger it moves to. + +- The move happens at once, without `openDelay`. +- For 400ms after a card closes, the next one still opens at once and without the pop. +- On its way to the open card, the pointer may cross another trigger. The card only moves when the pointer rests on that trigger for 150ms, so you can still reach the card you opened. +- When focus moves from the keyboard, the card swaps its content in place, with no motion. +- With reduced motion, the card stays in place and only the new content fades in. + +Because the card is shared, only one hover card is open at a time. A hover card inside another hover card, or one that must stay open next to another, needs its own surface: put it in a `HoverCardGroup` or pass `shared={false}`. + +### Groups + + + +`HoverCardGroup` gives the cards inside it a card of their own. Moving between triggers of the same group moves the group's card. The cards of a group never take over the page card or another group's card, so a card from each can be open at the same time. A card uses the nearest group above it; outside any group it uses the page card. + +`skipDelayDuration` sets how long after a card of the group closes the next one still opens at once. The page card uses 400ms. + +`shared={false}` gives one `HoverCard` a surface of its own, like a group with a single card. A card with `forceMount` always has its own. + ### List of entries @@ -67,12 +94,18 @@ A click opens the card at once, without `openDelay`. On a touch screen, the firs ### Controlled -Without `open`, the card manages its own state. To control it, pass `open` and `onOpenChange`. +Without `open`, the card manages its own state. To control it, pass `open` and `onOpenChange`. When another card takes over the shared surface, the card calls `onOpenChange(false)`. ## Ready API Import from `@codeui/kit/hover-card` or from `@codeui/kit`. +### `HoverCardGroup` + +Optional. Gives the cards inside it a surface of their own. + + + ### `HoverCard` Holds the open state, the hover and focus timers, and the position. @@ -89,7 +122,7 @@ Renders an `a`. Give it an `href`, or render another focusable element with `as` ### `HoverCardContent` -Portals the card to `document.body` and places it next to the trigger. +Renders its children into the shared card, which is portaled to `document.body` and placed next to the trigger. While this card is the one shown, its `class`, `classes`, `style`, `ref`, `mount` and dismiss handlers go on the card. Any other attribute or event handler, such as `id`, `aria-hidden` or `onPointerEnter`, goes on a `display: contents` element around the children. @@ -115,7 +148,7 @@ One line in a `HoverCardList`. | Key | Action | | --- | --- | -| Tab | Moving focus to the trigger opens the card after `openDelay`. Moving focus away closes it. | +| Tab | Moving focus to the trigger opens the card after `openDelay`. Moving focus away closes it. Moving focus to another trigger while the card is open moves the card there at once. | | Enter | Follows the link. A trigger rendered as a button opens the card. | | Escape | Closes the card. Focus stays on the trigger. | @@ -131,7 +164,7 @@ The card never takes focus. Focus stays on the trigger while it is open. ## SSR notes -The trigger renders on the server. The card renders on the client, and only while it is open. +The trigger renders on the server. The card renders on the client, and only while it is open. The page card is created the first time a card opens, in a `div` it appends to `document.body`. ## Theming hooks @@ -150,8 +183,9 @@ The trigger renders on the server. The card renders on the client, and only whil | `--cui-hovercard-item-indent` | `16px` | Indent per `depth` level | | `--cui-hovercard-item-depth` | Set from `depth` | Nesting level of one entry | | `--cui-motion-duration-normal`, `--cui-motion-duration-fast`, `--cui-motion-ease-out` | | Pop: in from `scale(0.96)` over 160ms, out to `scale(0.98)` over 120ms | +| `--cui-motion-duration-panel`, `--cui-motion-ease-out` | | Moving between cards: slide, resize and content fade over 200ms, ease-out | -A card opened by hover or click pops from the trigger side, with `transform-origin` from `--cui-popper-content-transform-origin`. A card opened by keyboard focus appears with no animation (`data-motion="none"`). With reduced motion, the card only fades. +A card opened by hover or click pops from the trigger side, with `transform-origin` from `--cui-popper-content-transform-origin`. A card opened by keyboard focus, or within 400ms of another card closing, appears with no animation (`data-motion="none"`). With reduced motion, the card only fades, and moving between cards only fades the new content in. Moving between cards from the keyboard has no motion. ## Related diff --git a/apps/docs/content/docs/design/patterns.mdx b/apps/docs/content/docs/design/patterns.mdx index 443cea83..c9eba246 100644 --- a/apps/docs/content/docs/design/patterns.mdx +++ b/apps/docs/content/docs/design/patterns.mdx @@ -71,7 +71,7 @@ A picker opens over the panel that holds it, anchored to its row. It does not pu A dialog is for settings and for decisions the user must make before continuing, such as reviewing detected secrets before an export. It is not for asking "are you sure?" about something that can be undone. -A tooltip is one line that names one thing. A description, or several facts about a row, goes in a hover card beside its trigger, on the right unless there is no room, wrapped at about 20rem. It opens on click too, so touch works, and everything in it is reachable another way. The `title` attribute is never used: it is slow, unstyled, and invisible to touch and keyboard. Use the kit [`HoverCard`](/docs/components/hover-card): it opens on hover, focus and click, sits on the right by default, and follows Pop. +A tooltip is one line that names one thing. A description, or several facts about a row, goes in a hover card beside its trigger, on the right unless there is no room, wrapped at about 20rem. It opens on click too, so touch works, and everything in it is reachable another way. The `title` attribute is never used: it is slow, unstyled, and invisible to touch and keyboard. Use the kit [`HoverCard`](/docs/components/hover-card): it opens on hover, focus and click, sits on the right by default, and follows Pop. Moving to the next trigger while a card is open moves that card instead of opening a second one: it slides to the new trigger and resizes to the new content. A list inside a menu or a hover card has one line per entry: state icon, identifier, title truncated. Nesting shows by indent, and a prefix that every entry shares is dropped. Two or more entries for the same action go in a submenu labelled with the count, so the menu does not fill up with "Open …" rows. A long list caps at about 24rem and scrolls on its own. In a hover card, build it with `HoverCardList` and `HoverCardItem`. diff --git a/apps/docs/export-manifest.json b/apps/docs/export-manifest.json index 3726c8d7..1a83b9e0 100644 --- a/apps/docs/export-manifest.json +++ b/apps/docs/export-manifest.json @@ -276,7 +276,9 @@ "HoverCardList": "components/hover-card#hovercardlist", "HoverCardListProps": "components/hover-card#hovercardlist", "TooltipDefaults": "components/tooltip#defaults-for-a-whole-app", - "TooltipProvider": "components/tooltip#defaults-for-a-whole-app" + "TooltipProvider": "components/tooltip#defaults-for-a-whole-app", + "HoverCardGroup": "components/hover-card#hovercardgroup", + "HoverCardGroupProps": "components/hover-card#hovercardgroup" }, "@codeui/kit/accordion/parts": { "AccordionClasses": "components/accordion#anatomy", @@ -1260,7 +1262,9 @@ "HoverCardItem": "components/hover-card#hovercarditem", "HoverCardItemProps": "components/hover-card#hovercarditem", "HoverCardList": "components/hover-card#hovercardlist", - "HoverCardListProps": "components/hover-card#hovercardlist" + "HoverCardListProps": "components/hover-card#hovercardlist", + "HoverCardGroup": "components/hover-card#hovercardgroup", + "HoverCardGroupProps": "components/hover-card#hovercardgroup" }, "@codeui/kit/resizable": { "Resizable": "components/resizable#resizable", diff --git a/packages/docs-demos/src/demos/hover-card/group.tsx b/packages/docs-demos/src/demos/hover-card/group.tsx new file mode 100644 index 00000000..ace15e16 --- /dev/null +++ b/packages/docs-demos/src/demos/hover-card/group.tsx @@ -0,0 +1,50 @@ +import { For } from "solid-js"; +import { + HoverCard, + HoverCardContent, + HoverCardGroup, + HoverCardTrigger, + Link, + Text, +} from "@codeui/kit"; + +const columns = [ + { name: "Files", items: ["fetch-retry.ts", "hover-card.tsx", "tokens.css"] }, + { name: "People", items: ["Ada Lovelace", "Grace Hopper", "Alan Turing"] }, +]; + +export default function HoverCardGroups() { + return ( +
+ + {column => ( + +
+ {column.name} + + {item => ( + + + {item} + + + + {item}, from the {column.name.toLowerCase()} group. + + + + )} + +
+
+ )} +
+
+ ); +} diff --git a/packages/docs-demos/src/demos/hover-card/shared.tsx b/packages/docs-demos/src/demos/hover-card/shared.tsx new file mode 100644 index 00000000..4c6f70f0 --- /dev/null +++ b/packages/docs-demos/src/demos/hover-card/shared.tsx @@ -0,0 +1,39 @@ +import { For } from "solid-js"; +import { HoverCard, HoverCardContent, HoverCardTrigger, Link, Text } from "@codeui/kit"; + +const threads = [ + { + id: "fix-flaky", + title: "Fix flaky hydration test", + detail: "Codex · 2 hours ago · 3 subagents", + }, + { id: "port-popover", title: "Port Popover to Solid 2", detail: "Claude · yesterday" }, + { + id: "docs-demos", + title: "Update the docs demos", + detail: + "Codex · 3 days ago · waiting for review. Checks every story in dark and light.", + }, +]; + +export default function HoverCardShared() { + return ( +
+ + {thread => ( + + + {thread.title} + + + {thread.title} + {thread.detail} + + + )} + +
+ ); +} diff --git a/packages/docs-demos/src/props/hover-card.ts b/packages/docs-demos/src/props/hover-card.ts index fff11c7f..a2c79cd5 100644 --- a/packages/docs-demos/src/props/hover-card.ts +++ b/packages/docs-demos/src/props/hover-card.ts @@ -1,5 +1,6 @@ import type { HoverCardContentProps, + HoverCardGroupProps, HoverCardItemProps, HoverCardProps, } from "@codeui/kit"; @@ -8,9 +9,12 @@ import type { PropNotes } from "./notes"; /** Props that HoverCard adds or changes on Kobalte's popover root. */ export type HoverCard = Pick< HoverCardProps, - "openDelay" | "closeDelay" | "ignoreSafeArea" + "openDelay" | "closeDelay" | "ignoreSafeArea" | "shared" >; +/** Props of the group that gives its hover cards a surface of their own. */ +export type HoverCardGroup = Pick; + /** Kobalte popover root options that change behavior. The kit sets the gutter default. */ export type HoverCardInherited = Pick< HoverCardProps, @@ -53,6 +57,18 @@ export const notes = { default: "false", description: "Closes as soon as the pointer leaves, even on its way to the card.", }, + shared: { + default: "true", + description: + "Shares one card with the page or the nearest HoverCardGroup. With false, the card has its own.", + }, + }, + HoverCardGroup: { + skipDelayDuration: { + default: "400", + description: + "Milliseconds after a card of the group closes during which the next one opens at once.", + }, }, HoverCardInherited: { open: { description: "Controlled open state." }, @@ -68,7 +84,9 @@ export const notes = { description: "Distance between the trigger and the card, in pixels.", }, shift: { default: "0", description: "Offset along the trigger edge, in pixels." }, - forceMount: { description: "Keeps the card in the DOM while it is closed." }, + forceMount: { + description: "Keeps the card in the DOM while it is closed. The card gets a surface of its own.", + }, }, HoverCardContent: { mount: { default: "document.body", description: "Node the card is portaled into." }, diff --git a/packages/kit/DESIGN.md b/packages/kit/DESIGN.md index 4425c0a9..1b02e0fe 100644 --- a/packages/kit/DESIGN.md +++ b/packages/kit/DESIGN.md @@ -365,7 +365,7 @@ No border; field fill, radius 12, padding 12; a 68px preview well (radius 8) ove - A picker opens anchored to its row, over the panel that holds it: 360px, radius 16, padding 16. - A dialog is for settings and for blocking decisions, not for confirming something undoable. -- A tooltip is one line that names one thing. A description, or more than one fact, goes in a hover card beside its trigger, on the right unless there is no room, wrapped at about 20rem. It opens on click too, so touch works. Never use the `title` attribute. Everything in a hover card is reachable another way. Use the kit `HoverCard`: `right-start` by default, a click or tap opens it at once, Pop motion, and the floating surface. +- A tooltip is one line that names one thing. A description, or more than one fact, goes in a hover card beside its trigger, on the right unless there is no room, wrapped at about 20rem. It opens on click too, so touch works. Never use the `title` attribute. Everything in a hover card is reachable another way. Use the kit `HoverCard`: `right-start` by default, a click or tap opens it at once, Pop motion, and the floating surface. Moving to the next trigger while a card is open moves that card: it slides to the new trigger and resizes to the new content in 200ms ease-out, with no second pop. From the keyboard it swaps in place. Hover cards share one card per page; a `HoverCardGroup` gives a set of triggers their own. - A list in a menu or hover card has one line per entry: state icon, identifier, title truncated. Show nesting by indent, and drop a prefix every entry shares. Two or more entries for one action go in a submenu labelled with the count. A long list caps at about 24rem and scrolls on its own. In a hover card, use `HoverCardList` and `HoverCardItem`; the icon slot stays when an entry has no icon. diff --git a/packages/kit/api/kit.api.md b/packages/kit/api/kit.api.md index f5378c49..dc9ae07c 100644 --- a/packages/kit/api/kit.api.md +++ b/packages/kit/api/kit.api.md @@ -4063,26 +4063,34 @@ export type FieldClasses = Partial & { +export { HoverCardGroup, type HoverCardGroupProps } from "./HoverCardHost.js"; +export type HoverCardProps = HoverCardPositioning & Pick & { /** Time in ms from when the pointer enters or the trigger gets focus until the card opens. Defaults to 500. */ openDelay?: number; /** Time in ms from when the pointer leaves the trigger and the card until it closes. Defaults to 150. */ closeDelay?: number; /** Close as soon as the pointer leaves, even on its way from the trigger to the card. */ ignoreSafeArea?: boolean; + /** + * Share the card with the other hover cards of the page, or of the nearest `HoverCardGroup`. + * Defaults to true. With false, or with `forceMount`, the card has a surface of its own. + */ + shared?: boolean; }; /** * Kobalte alpha.5's HoverCard root adds its pointer listener inside an effect * callback, which Solid 2 rejects as soon as the card opens. The card is built - * on Kobalte's Popover instead: Popper places it and its dismissable layer - * handles Escape and outside presses. The hover and focus timers below follow - * Kobalte's HoverCard. Return to `@kobalte/core/hover-card` once it registers - * the listener from an effect cleanup. + * on Kobalte's Popover instead, one popover shared by many cards (see + * `HoverCardHost`): Popper places it and its dismissable layer handles Escape + * and outside presses. The hover and focus timers below follow Kobalte's + * HoverCard. Return to `@kobalte/core/hover-card` once it registers the + * listener from an effect cleanup. */ export declare function HoverCard(props: ParentProps): JSX.Element; export type HoverCardTriggerProps = KPopoverAnchorProps & { @@ -4100,15 +4108,22 @@ export type HoverCardTriggerProps = KPopoverAnch * first tap on a closed card opens it instead of following the link; the next tap follows it. */ export declare function HoverCardTrigger(props: PolymorphicProps>): JSX.Element; -export type HoverCardContentProps = Omit, "onOpenAutoFocus" | "onCloseAutoFocus"> & { +export type HoverCardContentProps = Omit, "style"> & HoverCardDismissHandlers & { class?: string; + style?: JSX.CSSProperties | string; /** Node the card is portaled into. Defaults to `document.body`. */ mount?: globalThis.Element; /** Classes for the parts this component renders, keyed by part name. */ classes?: Pick; }; -/** The card. Portaled, placed beside the trigger (on the right unless there is no room), and never takes focus. */ -export declare function HoverCardContent(props: PolymorphicProps>): JSX.Element; +/** + * The card's content. It renders into the surface its `HoverCard` shares, which is portaled, + * placed beside the trigger (on the right unless there is no room), and never takes focus. + * Its class, style, ref and dismiss handlers go on that surface while this card is the one + * shown. Other attributes and event handlers go on a `display: contents` element that wraps + * the children inside it. + */ +export declare function HoverCardContent(props: HoverCardContentProps): JSX.Element; export type HoverCardListProps = JSX.HTMLAttributes & { /** Names the list for assistive technology, for example "Subtasks". */ "aria-label"?: string; @@ -4136,6 +4151,106 @@ export type HoverCardItemProps = Omit, "childr export declare function HoverCardItem(props: HoverCardItemProps): JSX.Element; ``` +## components/HoverCard/HoverCardHost.d.ts + +```ts +import { type HoverCardClasses } from "@codeui/styles/hovercard"; +import { type PopoverContentProps as KPopoverContentProps, type PopoverRootOptions as KPopoverRootOptions } from "@kobalte/core/popover"; +import { type Accessor, type ParentProps } from "solid-js"; +import { type JSX } from "@solidjs/web"; +export type HoverCardPositioning = Pick; +export type HoverCardDismissHandlers = Pick; +/** What the active card asks of the shared surface: its classes, attributes and handlers. */ +export type HoverCardSurfaceOptions = HoverCardDismissHandlers & { + class?: string; + classes?: Pick; + style?: JSX.CSSProperties | string; + mount?: globalThis.Element; + ref: (element: HTMLElement) => void; +}; +export type Point = { + x: number; + y: number; +}; +/** One `HoverCard` as the host sees it. */ +export type HoverCardEntry = { + trigger: Accessor; + positioning: HoverCardPositioning; + surface: Accessor; + /** True when the point is on the trigger, on the card, or on the way between them. */ + covers: (point: Point) => boolean; + /** The host showed another card or closed this one: update the card's own state. */ + dismiss: () => void; +}; +export declare const positioningKeys: (keyof HoverCardPositioning)[]; +type HostOptions = { + skipDelayDuration?: number; + forceMount?: boolean; + /** Renders the surface the first time a card opens. Hosts rendered in the tree leave it out. */ + mount?: (host: HoverCardHost) => void; +}; +type Size = { + width: number; + height: number; +}; +/** + * How the surface moves to the next card. A keyboard move swaps in place (Inkstone: nothing + * from the keyboard animates). Reduced motion keeps only the content fade. + */ +type Morph = { + kind: "move"; + from: Size; +} | { + kind: "fade"; +}; +/** + * One floating surface that every card of a group, or of the page, shares. + * Opening a card while another is open, or shortly after it closed, moves the + * surface to the new trigger and swaps the content instead of closing one card + * and opening another. + */ +export declare function createHoverCardHost(options?: HostOptions): { + current: import("solid-js").SourceAccessor; + open: import("solid-js").SourceAccessor; + surface: import("solid-js").SourceAccessor; + slot: import("solid-js").SourceAccessor; + setSlot: import("solid-js").Setter; + forceMount: () => boolean; + recentlyClosed: () => boolean; + setSurface(next: HTMLElement | undefined): void; + showing: (entry: HoverCardEntry) => boolean; + slotFor: (entry: HoverCardEntry) => HTMLElement | undefined; + /** 0 to open at once, or undefined to wait for the card's own `openDelay`. */ + openDelay(entry: HoverCardEntry, point?: Point): number | undefined; + /** Makes the entry the one whose content the surface holds, without opening it. */ + attach(entry: HoverCardEntry): void; + show(entry: HoverCardEntry): void; + hide(entry: HoverCardEntry): void; + /** Escape, a press outside, or a focus outside closed the surface. */ + dismiss(): void; + /** The card unmounted. Its content leaves with it, so the surface closes without an exit. */ + release(entry: HoverCardEntry): void; + takeMorph(): Morph | undefined; +}; +export type HoverCardHost = ReturnType; +/** The host of the nearest `HoverCardGroup`, or the one the whole page shares. */ +export declare function useHoverCardHost(): HoverCardHost; +export type HoverCardGroupProps = ParentProps<{ + /** Time in ms after a card closes during which the next card in the group opens at once. Defaults to 400. */ + skipDelayDuration?: number; +}>; +/** + * Gives the hover cards inside it their own surface. Moving between their triggers moves + * that card, and they never take over the surface of the cards outside the group. + */ +export declare function HoverCardGroup(props: HoverCardGroupProps): JSX.Element; +/** The popover the host places next to the active trigger. */ +export declare function HoverCardSurface(props: { + host: HoverCardHost; +}): JSX.Element; +export {}; +``` + ## components/IconButton/IconButton.d.ts ```ts diff --git a/packages/kit/src/components/HoverCard/HoverCard.tsx b/packages/kit/src/components/HoverCard/HoverCard.tsx index bbc54d2c..1fb82e1b 100644 --- a/packages/kit/src/components/HoverCard/HoverCard.tsx +++ b/packages/kit/src/components/HoverCard/HoverCard.tsx @@ -1,14 +1,11 @@ import "@codeui/styles/theme.css"; import "@codeui/styles/hovercard.css"; import { hoverCardParts, type HoverCardClasses } from "@codeui/styles/hovercard"; -import type { PolymorphicProps } from "@kobalte/core/polymorphic"; -import { callHandler, isPointInPolygon, type Polygon } from "@kobalte/utils"; -import { - Popover as KPopover, - usePopoverContext, - type PopoverAnchorProps as KPopoverAnchorProps, - type PopoverContentProps as KPopoverContentProps, - type PopoverRootOptions as KPopoverRootOptions, +import { Polymorphic, type PolymorphicProps } from "@kobalte/core/polymorphic"; +import { callHandler, isPointInPolygon } from "@kobalte/utils"; +import type { + PopoverAnchorProps as KPopoverAnchorProps, + PopoverRootOptions as KPopoverRootOptions, } from "@kobalte/core/popover"; import { createContext, @@ -21,12 +18,21 @@ import { useContext, type ParentProps, } from "solid-js"; -import { isServer, type JSX, type ValidComponent } from "@solidjs/web"; +import { isServer, Portal, type JSX, type ValidComponent } from "@solidjs/web"; import { mergeClasses } from "../../utils/css"; -import { HydratablePortal } from "../../utils/hydratable-portal"; -import { LayerScope } from "../../utils/layer-scope"; -import { createPopMotion, motionRef, PopMotionContext } from "../../utils/pop-motion"; import * as styles from "./HoverCard.css"; +import { + createHoverCardHost, + HoverCardSurface, + positioningKeys, + useHoverCardHost, + type HoverCardDismissHandlers, + type HoverCardEntry, + type HoverCardPositioning, + type HoverCardSurfaceOptions, + type Point, +} from "./HoverCardHost"; +import { safeArea } from "./safe-area"; export { hoverCardParts, @@ -35,28 +41,32 @@ export { type HoverCardClasses, type HoverCardStyles, } from "@codeui/styles/hovercard"; +export { HoverCardGroup, type HoverCardGroupProps } from "./HoverCardHost"; -export type HoverCardProps = Omit< - KPopoverRootOptions, - "modal" | "preventScroll" | "anchorRef" | "translations" -> & { - /** Time in ms from when the pointer enters or the trigger gets focus until the card opens. Defaults to 500. */ - openDelay?: number; - /** Time in ms from when the pointer leaves the trigger and the card until it closes. Defaults to 150. */ - closeDelay?: number; - /** Close as soon as the pointer leaves, even on its way from the trigger to the card. */ - ignoreSafeArea?: boolean; -}; +export type HoverCardProps = HoverCardPositioning & + Pick & { + /** Time in ms from when the pointer enters or the trigger gets focus until the card opens. Defaults to 500. */ + openDelay?: number; + /** Time in ms from when the pointer leaves the trigger and the card until it closes. Defaults to 150. */ + closeDelay?: number; + /** Close as soon as the pointer leaves, even on its way from the trigger to the card. */ + ignoreSafeArea?: boolean; + /** + * Share the card with the other hover cards of the page, or of the nearest `HoverCardGroup`. + * Defaults to true. With false, or with `forceMount`, the card has a surface of its own. + */ + shared?: boolean; + }; type HoverCardController = { - open: () => void; + open: (point?: Point) => void; openNow: () => void; isOpen: () => boolean; close: () => void; cancelOpen: () => void; - cancelClose: () => void; setTrigger: (element: HTMLElement) => void; - setContent: (element: HTMLElement) => void; + setSurface: (options: HoverCardSurfaceOptions | undefined) => void; + slot: () => HTMLElement | undefined; contains: (target: EventTarget | null) => boolean; }; @@ -64,45 +74,62 @@ const HoverCardContext = createContext(); function useHoverCard() { const context = useContext(HoverCardContext); - if (!context) throw new Error("[codeui]: HoverCard parts must be used within a `HoverCard`"); + if (!context) + throw new Error("[codeui]: HoverCard parts must be used within a `HoverCard`"); return context; } +function positioningFrom(props: HoverCardProps) { + const positioning = {} as HoverCardPositioning; + for (const key of positioningKeys) + Object.defineProperty(positioning, key, { enumerable: true, get: () => props[key] }); + return positioning; +} + +function inside(point: Point, rect: DOMRect) { + return ( + point.x >= rect.left && + point.x <= rect.right && + point.y >= rect.top && + point.y <= rect.bottom + ); +} + /** * Kobalte alpha.5's HoverCard root adds its pointer listener inside an effect * callback, which Solid 2 rejects as soon as the card opens. The card is built - * on Kobalte's Popover instead: Popper places it and its dismissable layer - * handles Escape and outside presses. The hover and focus timers below follow - * Kobalte's HoverCard. Return to `@kobalte/core/hover-card` once it registers - * the listener from an effect cleanup. + * on Kobalte's Popover instead, one popover shared by many cards (see + * `HoverCardHost`): Popper places it and its dismissable layer handles Escape + * and outside presses. The hover and focus timers below follow Kobalte's + * HoverCard. Return to `@kobalte/core/hover-card` once it registers the + * listener from an effect cleanup. */ export function HoverCard(props: ParentProps) { - const others = omit( - props, - "open", - "defaultOpen", - "onOpenChange", - "forceMount", - "openDelay", - "closeDelay", - "ignoreSafeArea", - ); - const [requested, setRequested] = createSignal(untrack(() => props.defaultOpen ?? false)); - const isOpen = () => props.open ?? requested(); - const motion = createPopMotion({ - get open() { - return isOpen(); - }, - get forceMount() { - return props.forceMount; - }, - onOpenChange(next: boolean) { - setRequested(next); - props.onOpenChange?.(next); + const ownSurface = untrack(() => props.shared === false || Boolean(props.forceMount)); + const host = ownSurface + ? createHoverCardHost({ + get forceMount() { + return props.forceMount; + }, + }) + : useHoverCardHost(); + const [requested, setRequested] = createSignal( + untrack(() => props.defaultOpen ?? false), + { + ownedWrite: true, }, + ); + const wanted = () => props.open ?? requested(); + let state = untrack(wanted); + const [trigger, setTrigger] = createSignal(undefined, { + ownedWrite: true, }); - const [trigger, setTrigger] = createSignal(); - const [content, setContent] = createSignal(); + const [surface, setSurface] = createSignal( + undefined, + { + ownedWrite: true, + }, + ); let openTimer: ReturnType | undefined; let closeTimer: ReturnType | undefined; @@ -117,20 +144,52 @@ export function HoverCard(props: ParentProps) { const setOpen = (next: boolean) => { cancelOpen(); cancelClose(); - if (next !== isOpen()) motion.onOpenChange(next); + if (next === state) return; + state = next; + setRequested(next); + props.onOpenChange?.(next); + }; + const covers = (point: Point) => { + const anchor = trigger(); + const card = untrack(host.surface); + if (!anchor || !card) return false; + if (inside(point, anchor.getBoundingClientRect())) return true; + if (inside(point, card.getBoundingClientRect())) return true; + return ( + !props.ignoreSafeArea && + isPointInPolygon([point.x, point.y], safeArea(anchor, card)) + ); + }; + const entry: HoverCardEntry = { + trigger, + positioning: positioningFrom(props), + surface, + covers, + dismiss: () => setOpen(false), + }; + const isOpen = () => host.showing(entry); + const show = () => { + cancelOpen(); + cancelClose(); + if (state) host.show(entry); + else setOpen(true); }; const contains = (target: EventTarget | null) => target instanceof Node && - Boolean(trigger()?.contains(target) || content()?.contains(target)); + Boolean( + trigger()?.contains(target) || (isOpen() && host.surface()?.contains(target)), + ); const controller: HoverCardController = { - open() { + open(point) { cancelClose(); if (isOpen() || openTimer) return; - openTimer = setTimeout(() => setOpen(true), props.openDelay ?? 500); + const delay = host.openDelay(entry, point) ?? props.openDelay ?? 500; + if (delay <= 0) return show(); + openTimer = setTimeout(show, delay); }, openNow() { - if (!isOpen()) setOpen(true); + if (!isOpen()) show(); else cancelClose(); }, isOpen, @@ -140,14 +199,20 @@ export function HoverCard(props: ParentProps) { closeTimer = setTimeout(() => setOpen(false), props.closeDelay ?? 150); }, cancelOpen, - cancelClose, setTrigger, - setContent, + setSurface, + slot: () => host.slotFor(entry), contains, }; + if (ownSurface) host.attach(entry); + createEffect(wanted, open => { + state = open; + if (open) host.show(entry); + else host.hide(entry); + }); createEffect( - () => (isOpen() ? { trigger: trigger(), content: content() } : undefined), + () => (isOpen() ? { trigger: trigger(), content: host.surface() } : undefined), elements => { if (isServer || !elements) return; const onPointerMove = (event: PointerEvent) => { @@ -170,33 +235,29 @@ export function HoverCard(props: ParentProps) { onCleanup(() => { cancelOpen(); cancelClose(); + host.release(entry); }); return ( - - - + {props.children} + + + ); } -export type HoverCardTriggerProps = KPopoverAnchorProps & { - class?: string; - onPointerEnter?: JSX.EventHandlerUnion; - onPointerLeave?: JSX.EventHandlerUnion; - onFocus?: JSX.EventHandlerUnion; - onBlur?: JSX.EventHandlerUnion; - onPointerDown?: JSX.EventHandlerUnion; - onClick?: JSX.EventHandlerUnion; -}; +export type HoverCardTriggerProps = + KPopoverAnchorProps & { + class?: string; + onPointerEnter?: JSX.EventHandlerUnion; + onPointerLeave?: JSX.EventHandlerUnion; + onFocus?: JSX.EventHandlerUnion; + onBlur?: JSX.EventHandlerUnion; + onPointerDown?: JSX.EventHandlerUnion; + onClick?: JSX.EventHandlerUnion; + }; type TriggerEvent = E & { currentTarget: HTMLElement; target: Element }; @@ -223,13 +284,16 @@ export function HoverCardTrigger( const card = useHoverCard(); let pointerType = ""; return ( - ) => { callHandler(event, local.onPointerEnter); - if (event.pointerType !== "touch" && !event.defaultPrevented) card.open(); + if (event.pointerType !== "touch" && !event.defaultPrevented) + card.open({ x: event.clientX, y: event.clientY }); }} onPointerLeave={(event: TriggerEvent) => { callHandler(event, local.onPointerLeave); @@ -262,66 +326,76 @@ export function HoverCardTrigger( ); } -export type HoverCardContentProps = Omit< - KPopoverContentProps, - "onOpenAutoFocus" | "onCloseAutoFocus" -> & { - class?: string; - /** Node the card is portaled into. Defaults to `document.body`. */ - mount?: globalThis.Element; - /** Classes for the parts this component renders, keyed by part name. */ - classes?: Pick; -}; +export type HoverCardContentProps = Omit, "style"> & + HoverCardDismissHandlers & { + class?: string; + style?: JSX.CSSProperties | string; + /** Node the card is portaled into. Defaults to `document.body`. */ + mount?: globalThis.Element; + /** Classes for the parts this component renders, keyed by part name. */ + classes?: Pick; + }; -type PointerDownOutsideEvent = Parameters< - NonNullable ->[0]; +function applyRef(ref: unknown, element: HTMLElement) { + if (Array.isArray(ref)) for (const each of ref) applyRef(each, element); + else if (typeof ref === "function") ref(element); +} -/** The card. Portaled, placed beside the trigger (on the right unless there is no room), and never takes focus. */ -export function HoverCardContent( - props: PolymorphicProps>, -) { - const local = props as PolymorphicProps<"div", HoverCardContentProps>; - const others = omit(local, "class", "classes", "mount", "ref", "onPointerDownOutside"); - const popover = usePopoverContext(); +/** + * The card's content. It renders into the surface its `HoverCard` shares, which is portaled, + * placed beside the trigger (on the right unless there is no room), and never takes focus. + * Its class, style, ref and dismiss handlers go on that surface while this card is the one + * shown. Other attributes and event handlers go on a `display: contents` element that wraps + * the children inside it. + */ +export function HoverCardContent(props: HoverCardContentProps) { const card = useHoverCard(); + const attributes = omit( + props, + "class", + "classes", + "style", + "mount", + "ref", + "children", + "onEscapeKeyDown", + "onPointerDownOutside", + "onFocusOutside", + "onInteractOutside", + ); + card.setSurface({ + get class() { + return props.class; + }, + get classes() { + return props.classes; + }, + get style() { + return props.style; + }, + get mount() { + return props.mount; + }, + ref: element => applyRef(props.ref, element), + onEscapeKeyDown: event => props.onEscapeKeyDown?.(event), + onPointerDownOutside: event => props.onPointerDownOutside?.(event), + onFocusOutside: event => props.onFocusOutside?.(event), + onInteractOutside: event => props.onInteractOutside?.(event), + }); + onCleanup(() => card.setSurface(undefined)); return ( - - - - { - local.onPointerDownOutside?.(event); - // A press on the trigger is a click that keeps the card open. - if (card.contains(event.target)) event.preventDefault(); - }} - data-cui={hoverCardParts.content} - class={mergeClasses(styles.content(), local.classes?.content, local.class)} - /> - - + + {slot => ( + +
+ {props.children} +
+
+ )}
); } -/** The region the pointer may cross from the trigger to the card without closing it, after Kobalte's HoverCard. */ -function safeArea(trigger: HTMLElement, content: HTMLElement): Polygon { - const a = trigger.getBoundingClientRect(); - const f = content.getBoundingClientRect(); - const centerX = a.left + a.width / 2; - const centerY = a.top + a.height / 2; - if (f.left >= a.right) - return [[centerX, a.top], [f.left, f.top], [f.right, f.top], [f.right, f.bottom], [f.left, f.bottom], [centerX, a.bottom]]; - if (f.right <= a.left) - return [[centerX, a.top], [f.right, f.top], [f.left, f.top], [f.left, f.bottom], [f.right, f.bottom], [centerX, a.bottom]]; - if (f.top >= a.bottom) - return [[a.left, centerY], [f.left, f.top], [f.left, f.bottom], [f.right, f.bottom], [f.right, f.top], [a.right, centerY]]; - return [[a.left, centerY], [f.left, f.bottom], [f.left, f.top], [f.right, f.top], [f.right, f.bottom], [a.right, centerY]]; -} - export type HoverCardListProps = JSX.HTMLAttributes & { /** Names the list for assistive technology, for example "Subtasks". */ "aria-label"?: string; diff --git a/packages/kit/src/components/HoverCard/HoverCardHost.tsx b/packages/kit/src/components/HoverCard/HoverCardHost.tsx new file mode 100644 index 00000000..94604bb5 --- /dev/null +++ b/packages/kit/src/components/HoverCard/HoverCardHost.tsx @@ -0,0 +1,451 @@ +import { hoverCardParts, type HoverCardClasses } from "@codeui/styles/hovercard"; +import { + Popover as KPopover, + usePopoverContext, + type PopoverContentProps as KPopoverContentProps, + type PopoverRootOptions as KPopoverRootOptions, +} from "@kobalte/core/popover"; +import { + createContext, + createEffect, + createMemo, + createSignal, + Show, + untrack, + useContext, + type Accessor, + type ParentProps, +} from "solid-js"; +import { isServer, render, type JSX } from "@solidjs/web"; +import { mergeClasses } from "../../utils/css"; +import { HydratablePortal } from "../../utils/hydratable-portal"; +import { LayerScope } from "../../utils/layer-scope"; +import { pointerInitiated } from "../../utils/open-source"; +import { createPopMotion, motionRef, PopMotionContext } from "../../utils/pop-motion"; +import * as styles from "./HoverCard.css"; + +export type HoverCardPositioning = Pick< + KPopoverRootOptions, + | "placement" + | "gutter" + | "shift" + | "flip" + | "slide" + | "overlap" + | "sameWidth" + | "fitViewport" + | "hideWhenDetached" + | "detachedPadding" + | "arrowPadding" + | "overflowPadding" + | "getAnchorRect" +>; + +export type HoverCardDismissHandlers = Pick< + KPopoverContentProps, + "onEscapeKeyDown" | "onPointerDownOutside" | "onFocusOutside" | "onInteractOutside" +>; + +/** What the active card asks of the shared surface: its classes, attributes and handlers. */ +export type HoverCardSurfaceOptions = HoverCardDismissHandlers & { + class?: string; + classes?: Pick; + style?: JSX.CSSProperties | string; + mount?: globalThis.Element; + ref: (element: HTMLElement) => void; +}; + +export type Point = { x: number; y: number }; + +/** One `HoverCard` as the host sees it. */ +export type HoverCardEntry = { + trigger: Accessor; + positioning: HoverCardPositioning; + surface: Accessor; + /** True when the point is on the trigger, on the card, or on the way between them. */ + covers: (point: Point) => boolean; + /** The host showed another card or closed this one: update the card's own state. */ + dismiss: () => void; +}; + +const defaultSkipDelay = 400; +/** How long the pointer rests on another trigger, while still on the way to the open card, before the card moves. */ +const retargetDelay = 150; + +const popperDefaults: Required = { + placement: "right-start", + gutter: 6, + shift: 0, + flip: true, + slide: true, + overlap: false, + sameWidth: false, + fitViewport: false, + hideWhenDetached: false, + detachedPadding: 0, + arrowPadding: 4, + overflowPadding: 8, + getAnchorRect: anchor => anchor?.getBoundingClientRect(), +}; +export const positioningKeys = Object.keys( + popperDefaults, +) as (keyof HoverCardPositioning)[]; + +type HostOptions = { + skipDelayDuration?: number; + forceMount?: boolean; + /** Renders the surface the first time a card opens. Hosts rendered in the tree leave it out. */ + mount?: (host: HoverCardHost) => void; +}; + +type Size = { width: number; height: number }; + +/** The layout size, without the scale of a pop that may still be running. */ +function sizeOf(element: HTMLElement): Size { + return { width: element.offsetWidth, height: element.offsetHeight }; +} + +/** Inkstone §7.3: a content change takes the panel duration and the kit's ease-out. */ +const slide = "transform var(--cui-motion-duration-panel) var(--cui-motion-ease-out)"; + +/** + * How the surface moves to the next card. A keyboard move swaps in place (Inkstone: nothing + * from the keyboard animates). Reduced motion keeps only the content fade. + */ +type Morph = { kind: "move"; from: Size } | { kind: "fade" }; + +function reducedMotion() { + return matchMedia("(prefers-reduced-motion: reduce)").matches; +} + +/** + * One floating surface that every card of a group, or of the page, shares. + * Opening a card while another is open, or shortly after it closed, moves the + * surface to the new trigger and swaps the content instead of closing one card + * and opening another. + */ +export function createHoverCardHost(options: HostOptions = {}) { + const [current, setCurrent] = createSignal(undefined, { + ownedWrite: true, + }); + const [open, setOpen] = createSignal(false, { ownedWrite: true }); + const [surface, setSurface] = createSignal(undefined, { + ownedWrite: true, + }); + const [slot, setSlot] = createSignal(undefined, { + ownedWrite: true, + }); + let shown: HoverCardEntry | undefined; + let isOpen = false; + let lastClosed = -Infinity; + let element: HTMLElement | undefined; + let morph: Morph | undefined; + + const recentlyClosed = () => + performance.now() - lastClosed < (options.skipDelayDuration ?? defaultSkipDelay); + const close = () => { + if (!isOpen) return; + isOpen = false; + lastClosed = performance.now(); + setOpen(false); + }; + const startMorph = (from: HTMLElement) => { + if (!pointerInitiated({ hover: true })) return; + if (reducedMotion()) { + morph = { kind: "fade" }; + return; + } + morph = { kind: "move", from: sizeOf(from) }; + const positioner = from.parentElement; + if (positioner) positioner.style.transition = slide; + }; + + const host = { + current, + open, + surface, + slot, + setSlot, + forceMount: () => options.forceMount ?? false, + recentlyClosed, + setSurface(next: HTMLElement | undefined) { + element = next; + setSurface(next); + }, + showing: (entry: HoverCardEntry) => open() && current() === entry, + slotFor: (entry: HoverCardEntry) => (current() === entry ? slot() : undefined), + /** 0 to open at once, or undefined to wait for the card's own `openDelay`. */ + openDelay(entry: HoverCardEntry, point?: Point): number | undefined { + if (isOpen && shown && shown !== entry) + return point && shown.covers(point) ? retargetDelay : 0; + return recentlyClosed() ? 0 : undefined; + }, + /** Makes the entry the one whose content the surface holds, without opening it. */ + attach(entry: HoverCardEntry) { + if (shown) return; + shown = entry; + setCurrent(() => entry); + }, + show(entry: HoverCardEntry) { + if (isOpen && shown === entry) return; + options.mount?.(host); + const previous = shown; + const previousOpen = isOpen; + if (previous && previous !== entry && element?.isConnected) startMorph(element); + shown = entry; + isOpen = true; + setCurrent(() => entry); + setOpen(true); + if (previous && previous !== entry && previousOpen) previous.dismiss(); + }, + hide(entry: HoverCardEntry) { + if (shown === entry) close(); + }, + /** Escape, a press outside, or a focus outside closed the surface. */ + dismiss() { + const entry = shown; + close(); + entry?.dismiss(); + }, + /** The card unmounted. Its content leaves with it, so the surface closes without an exit. */ + release(entry: HoverCardEntry) { + if (shown !== entry) return; + element?.setAttribute("data-motion", "none"); + shown = undefined; + isOpen = false; + setOpen(false); + setCurrent(undefined); + }, + takeMorph() { + const next = morph; + morph = undefined; + return next; + }, + }; + return host; +} + +export type HoverCardHost = ReturnType; + +const HostContext = createContext(null); + +let pageHost: HoverCardHost | undefined; + +function mountPageSurface(host: HoverCardHost) { + let mounted = false; + return () => { + if (mounted) return; + mounted = true; + // Out of the effect that opened the card, so `render` does not flush inside it. + queueMicrotask(() => { + const container = document.createElement("div"); + container.setAttribute("data-cui", "hovercard-host"); + container.style.display = "contents"; + document.body.append(container); + render(() => , container); + }); + }; +} + +/** The host of the nearest `HoverCardGroup`, or the one the whole page shares. */ +export function useHoverCardHost(): HoverCardHost { + const group = useContext(HostContext); + if (group) return group; + if (isServer) return createHoverCardHost(); + if (!pageHost) { + let mount: (() => void) | undefined; + pageHost = createHoverCardHost({ mount: () => mount?.() }); + mount = mountPageSurface(pageHost); + } + return pageHost; +} + +export type HoverCardGroupProps = ParentProps<{ + /** Time in ms after a card closes during which the next card in the group opens at once. Defaults to 400. */ + skipDelayDuration?: number; +}>; + +/** + * Gives the hover cards inside it their own surface. Moving between their triggers moves + * that card, and they never take over the surface of the cards outside the group. + */ +export function HoverCardGroup(props: HoverCardGroupProps) { + const host = createHoverCardHost({ + get skipDelayDuration() { + return props.skipDelayDuration; + }, + }); + return ( + + {props.children} + + + ); +} + +function positioningOf(entry: Accessor) { + const positioning = {} as Required; + for (const key of positioningKeys) + Object.defineProperty(positioning, key, { + enumerable: true, + get: () => entry()?.positioning[key] ?? popperDefaults[key], + }); + return positioning; +} + +/** The popover the host places next to the active trigger. */ +export function HoverCardSurface(props: { host: HoverCardHost }) { + const host = untrack(() => props.host); + const motion = createPopMotion({ + get open() { + return host.open(); + }, + get forceMount() { + return host.forceMount(); + }, + onOpenChange(next: boolean) { + if (!next) host.dismiss(); + }, + }); + return ( + + host.current()?.trigger()} + > + + + + ); +} + +type PointerDownOutsideEvent = Parameters< + NonNullable +>[0]; + +function SurfaceContent(props: { host: HoverCardHost }) { + const host = untrack(() => props.host); + const popover = usePopoverContext(); + const options = () => host.current()?.surface(); + const mount = createMemo(() => options()?.mount); + createMorph(host); + createEffect( + () => ({ element: host.surface(), ref: options()?.ref }), + ({ element, ref }) => { + if (element && ref) ref(element); + }, + ); + return ( + + + + + options()?.onEscapeKeyDown?.(event) + } + onPointerDownOutside={(event: PointerDownOutsideEvent) => { + options()?.onPointerDownOutside?.(event); + // A press on a trigger is a click that keeps the card open or moves it there. + if (onTrigger(event.target)) event.preventDefault(); + }} + onFocusOutside={( + event: Parameters>[0], + ) => { + options()?.onFocusOutside?.(event); + // Focus on another trigger moves the card there. Leaving the previous + // trigger closes it through its blur handler and closeDelay instead. + if (onTrigger(event.target)) event.preventDefault(); + }} + onInteractOutside={( + event: Parameters< + NonNullable + >[0], + ) => options()?.onInteractOutside?.(event)} + data-cui={hoverCardParts.content} + class={mergeClasses( + styles.content(), + options()?.classes?.content, + options()?.class, + )} + > +
+ + + + + ); +} + +function onTrigger(target: EventTarget | null) { + return ( + target instanceof Element && + Boolean(target.closest(`[data-cui=${hoverCardParts.trigger}]`)) + ); +} + +function motionTiming(element: HTMLElement): KeyframeAnimationOptions { + const style = getComputedStyle(element); + const raw = style.getPropertyValue("--cui-motion-duration-panel").trim(); + const value = Number.parseFloat(raw); + const duration = Number.isFinite(value) + ? raw.endsWith("ms") + ? value + : value * 1000 + : 200; + const easing = style.getPropertyValue("--cui-motion-ease-out").trim() || "ease-out"; + return { duration, easing }; +} + +/** + * When the surface moves to another card it keeps its old size for a moment and + * grows or shrinks to the new one while the new content fades in. The positioner's + * transform transition, set when the move starts, slides it to the new trigger. + * Width and height animate because the card's text has to reflow at its real size: + * a scale would stretch it. The card is small and the change lasts 200ms, like the + * accordion's height in Inkstone's Expand. + */ +function createMorph(host: HoverCardHost) { + createEffect( + () => host.current(), + () => { + const morph = host.takeMorph(); + const surface = untrack(host.surface); + const positioner = surface?.parentElement; + if (!morph || !surface) return; + const timing = motionTiming(surface); + const animations: Animation[] = []; + if (morph.kind === "move") { + if (positioner) positioner.style.transition = slide; + const to = sizeOf(surface); + animations.push( + surface.animate( + [ + { width: `${morph.from.width}px`, height: `${morph.from.height}px` }, + { width: `${to.width}px`, height: `${to.height}px` }, + ], + timing, + ), + ); + } + for (const child of untrack(host.slot)?.children ?? []) + animations.push(child.animate([{ opacity: 0 }, { opacity: 1 }], timing)); + const settle = setTimeout(() => { + if (positioner) positioner.style.transition = ""; + }, Number(timing.duration)); + return () => { + clearTimeout(settle); + for (const animation of animations) animation.cancel(); + if (positioner) positioner.style.transition = ""; + }; + }, + ); +} diff --git a/packages/kit/src/components/HoverCard/safe-area.ts b/packages/kit/src/components/HoverCard/safe-area.ts new file mode 100644 index 00000000..1b7a6bd8 --- /dev/null +++ b/packages/kit/src/components/HoverCard/safe-area.ts @@ -0,0 +1,16 @@ +import type { Polygon } from "@kobalte/utils"; + +/** The region the pointer may cross from the trigger to the card without closing it, after Kobalte's HoverCard. */ +export function safeArea(trigger: HTMLElement, content: HTMLElement): Polygon { + const a = trigger.getBoundingClientRect(); + const f = content.getBoundingClientRect(); + const centerX = a.left + a.width / 2; + const centerY = a.top + a.height / 2; + if (f.left >= a.right) + return [[centerX, a.top], [f.left, f.top], [f.right, f.top], [f.right, f.bottom], [f.left, f.bottom], [centerX, a.bottom]]; + if (f.right <= a.left) + return [[centerX, a.top], [f.right, f.top], [f.left, f.top], [f.left, f.bottom], [f.right, f.bottom], [centerX, a.bottom]]; + if (f.top >= a.bottom) + return [[a.left, centerY], [f.left, f.top], [f.left, f.bottom], [f.right, f.bottom], [f.right, f.top], [a.right, centerY]]; + return [[a.left, centerY], [f.left, f.bottom], [f.left, f.top], [f.right, f.top], [f.right, f.bottom], [a.right, centerY]]; +} diff --git a/packages/kit/src/utils/open-source.ts b/packages/kit/src/utils/open-source.ts index 93206267..2e46d49c 100644 --- a/packages/kit/src/utils/open-source.ts +++ b/packages/kit/src/utils/open-source.ts @@ -18,6 +18,9 @@ export function trackInput() { }; const options = { capture: true, passive: true }; document.addEventListener("pointerdown", record("press"), options); + // The browser fires pointerover before the pointermove that crosses into an element, + // so an overlay opened from pointerenter sees this pointer, not the previous one. + document.addEventListener("pointerover", record("hover"), options); document.addEventListener("pointermove", record("hover"), options); document.addEventListener("keydown", record("key"), options); } diff --git a/packages/kit/test/hover-card-shared.test.tsx b/packages/kit/test/hover-card-shared.test.tsx new file mode 100644 index 00000000..20573286 --- /dev/null +++ b/packages/kit/test/hover-card-shared.test.tsx @@ -0,0 +1,196 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; +import { createSignal, Show } from "solid-js"; +import { + HoverCard, + HoverCardContent, + HoverCardGroup, + HoverCardTrigger, +} from "../src/components/HoverCard/HoverCard"; +import { press } from "./helpers"; + +const cards = () => [ + ...document.querySelectorAll("[data-cui=hovercard-content]"), +]; +const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + +// Cards outside a group share one page surface. Let the previous test's card leave +// and its skip window pass, so each test starts from a closed page card. +beforeEach(async () => { + await waitFor(() => expect(cards()).toHaveLength(0)); + await sleep(450); +}); +afterEach(cleanup); + +function hover(trigger: HTMLElement, point?: { x: number; y: number }) { + const rect = trigger.getBoundingClientRect(); + const { x, y } = point ?? { x: rect.left + 2, y: rect.top + 2 }; + fireEvent.pointerMove(document, { pointerType: "mouse" }); + fireEvent.pointerEnter(trigger, { pointerType: "mouse", clientX: x, clientY: y }); +} + +function Pair(props: { onA?: (open: boolean) => void; delayB?: number }) { + return ( +
+ + + Thread A + + +
Details of A
+
+
+ + + Thread B + + Details of B + +
+ ); +} + +async function openA() { + const a = screen.getByRole("link", { name: "Thread A" }); + hover(a); + await waitFor(() => expect(cards()[0]).toHaveTextContent("Details of A")); + return cards()[0]; +} + +it("moves the open card to the next trigger at once, as the same element", async () => { + const onA = vi.fn(); + render(() => ); + const surface = await openA(); + hover(screen.getByRole("link", { name: "Thread B" })); + await waitFor(() => expect(surface).toHaveTextContent("Details of B"), { + timeout: 200, + }); + expect(cards()).toEqual([surface]); + expect(surface).not.toHaveTextContent("Details of A"); + expect(surface).toContainElement(document.getElementById("card-b")); + expect(document.getElementById("card-a")).toBeNull(); + expect(onA).toHaveBeenLastCalledWith(false); +}); + +it("slides and resizes the card while it moves", async () => { + render(() => ); + const surface = await openA(); + const from = surface.offsetHeight; + hover(screen.getByRole("link", { name: "Thread B" })); + await waitFor(() => expect(surface).toHaveTextContent("Details of B")); + expect(surface.parentElement!.style.transition).toContain("transform"); + const resize = surface.getAnimations().find(animation => { + const [first] = (animation.effect as KeyframeEffect).getKeyframes(); + return first.height === `${from}px`; + }); + expect(resize).toBeDefined(); + await waitFor(() => expect(surface.parentElement!.style.transition).toBe("")); +}); + +it("moves in place, without the slide or the fade, when focus moves from the keyboard", async () => { + render(() => ); + const a = screen.getByRole("link", { name: "Thread A" }); + const b = screen.getByRole("link", { name: "Thread B" }); + press("Tab"); + a.focus(); + await waitFor(() => expect(cards()[0]).toHaveTextContent("Details of A")); + const surface = cards()[0]; + press("Tab"); + b.focus(); + await waitFor(() => expect(surface).toHaveTextContent("Details of B"), { + timeout: 200, + }); + expect(surface.parentElement!.style.transition).toBe(""); + expect(surface.getAnimations()).toHaveLength(0); + await sleep(300); + expect(cards()).toEqual([surface]); + expect(surface).toHaveTextContent("Details of B"); +}); + +it("waits before moving while the pointer is on its way to the open card", async () => { + render(() => ); + const surface = await openA(); + const a = screen.getByRole("link", { name: "Thread A" }).getBoundingClientRect(); + const card = surface.getBoundingClientRect(); + hover(screen.getByRole("link", { name: "Thread B" }), { + x: card.left - 1, + y: a.bottom + 4, + }); + await sleep(60); + expect(surface).toHaveTextContent("Details of A"); + await waitFor(() => expect(surface).toHaveTextContent("Details of B"), { + timeout: 400, + }); +}); + +it("opens the next card at once, without the pop, shortly after one closes", async () => { + render(() => ); + await openA(); + press("Escape"); + await waitFor(() => expect(cards()).toHaveLength(0)); + hover(screen.getByRole("link", { name: "Thread B" })); + await waitFor(() => expect(cards()[0]).toHaveTextContent("Details of B"), { + timeout: 200, + }); + expect(cards()[0]).toHaveAttribute("data-motion", "none"); +}); + +it("waits for openDelay again once the skip window has passed", async () => { + render(() => ); + await openA(); + press("Escape"); + await waitFor(() => expect(cards()).toHaveLength(0)); + await sleep(450); + hover(screen.getByRole("link", { name: "Thread B" })); + await sleep(150); + expect(cards()).toHaveLength(0); + await waitFor(() => expect(cards()[0]).toHaveTextContent("Details of B"), { + timeout: 600, + }); +}); + +it("keeps the cards of a group apart from the page card", async () => { + render(() => ( + <> + + + + Thread C + Details of C + + + + )); + await openA(); + hover(screen.getByRole("link", { name: "Thread C" })); + await waitFor(() => expect(cards()).toHaveLength(2)); + expect(cards().map(card => card.textContent)).toEqual(["Details of A", "Details of C"]); +}); + +it("gives a card with shared={false} a surface of its own", async () => { + render(() => ( + <> + + + Thread D + Details of D + + + )); + await openA(); + hover(screen.getByRole("link", { name: "Thread D" })); + await waitFor(() => expect(cards()).toHaveLength(2)); +}); + +it("closes the page card when the open HoverCard unmounts", async () => { + const [shown, setShown] = createSignal(true); + render(() => ( + + + + )); + await openA(); + setShown(false); + await waitFor(() => expect(cards()).toHaveLength(0), { timeout: 200 }); +}); diff --git a/packages/kit/test/hover-card.test.tsx b/packages/kit/test/hover-card.test.tsx index 10741b64..ffbd2d95 100644 --- a/packages/kit/test/hover-card.test.tsx +++ b/packages/kit/test/hover-card.test.tsx @@ -2,6 +2,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-li import { HoverCard, HoverCardContent, + HoverCardGroup, HoverCardItem, HoverCardList, HoverCardTrigger, @@ -14,10 +15,12 @@ const card = () => document.querySelector("[data-cui=hovercard-cont function renderCard(props: { openDelay?: number; closeDelay?: number } = {}) { render(() => ( - - Fix flaky test - Opened 2 hours ago by Codex - + + + Fix flaky test + Opened 2 hours ago by Codex + + )); return screen.getByRole("link", { name: "Fix flaky test" }); } diff --git a/packages/storybook/src/stories/HoverCard.stories.tsx b/packages/storybook/src/stories/HoverCard.stories.tsx index bfc38221..5b581c2e 100644 --- a/packages/storybook/src/stories/HoverCard.stories.tsx +++ b/packages/storybook/src/stories/HoverCard.stories.tsx @@ -3,6 +3,7 @@ import type { Meta, StoryObj } from "storybook-solidjs-vite"; import { HoverCard, HoverCardContent, + HoverCardGroup, HoverCardItem, HoverCardList, HoverCardTrigger, @@ -179,3 +180,66 @@ export const EdgePlacement: Story = {
), }; + +const threads = [ + { id: "flaky", title: "Fix flaky hydration test", meta: "Codex · 2 hours ago · 3 subagents" }, + { id: "popover", title: "Port Popover to Solid 2", meta: "Claude · yesterday" }, + { + id: "docs", + title: "Update the docs demos", + meta: "Codex · 3 days ago", + body: "Checks every story in dark and light themes at three viewport sizes, then opens a pull request for review.", + }, + { id: "tokens", title: "Rename motion tokens", meta: "Claude · last week" }, +]; + +const ThreadRows = () => ( +
+ + {thread => ( + + + {thread.title} + + + + {thread.title} + + + {thread.meta} + + {thread.body && {thread.body}} + + + )} + +
+); + +export const SharedCard: Story = { + name: "Moving between rows", + args: {}, + render: () => ( +
+ +
+ ), +}; + +export const Groups: Story = { + name: "Two groups", + args: {}, + render: () => ( +
+ + + + + + +
+ ), +}; From f5c9498e70e17d98a540d846bb52922ed2dd11b2 Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Sat, 28 Nov 2026 13:10:13 +0100 Subject: [PATCH 2/3] docs(hover-card): keep demo links at their own width so the card sits beside them Co-Authored-By: Claude Opus 5.5 --- packages/docs-demos/src/demos/hover-card/group.tsx | 1 + packages/docs-demos/src/demos/hover-card/shared.tsx | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/docs-demos/src/demos/hover-card/group.tsx b/packages/docs-demos/src/demos/hover-card/group.tsx index ace15e16..7317b9e9 100644 --- a/packages/docs-demos/src/demos/hover-card/group.tsx +++ b/packages/docs-demos/src/demos/hover-card/group.tsx @@ -23,6 +23,7 @@ export default function HoverCardGroups() { style={{ display: "flex", "flex-direction": "column", + "align-items": "flex-start", gap: "var(--cui-space-2)", }} > diff --git a/packages/docs-demos/src/demos/hover-card/shared.tsx b/packages/docs-demos/src/demos/hover-card/shared.tsx index 4c6f70f0..007afb56 100644 --- a/packages/docs-demos/src/demos/hover-card/shared.tsx +++ b/packages/docs-demos/src/demos/hover-card/shared.tsx @@ -19,7 +19,12 @@ const threads = [ export default function HoverCardShared() { return (
{thread => ( From a5340668cca2e644d1c2966e72f2231028026f15 Mon Sep 17 00:00:00 2001 From: riccardoperra Date: Sat, 28 Nov 2026 13:16:14 +0100 Subject: [PATCH 3/3] feat(kit): nested hover cards and a dotted underline on text triggers A hover card inside another card's content gets a surface of its own. The outer card stays open while the pointer is on the inner card and until it closes; a press on the inner card no longer dismisses it, and Escape closes the inner card first. An `a` trigger gets a dotted underline in the hint tone that takes the text colour on hover and while open, so hover-card links read as such in running text. Button and row triggers keep their own look. Co-Authored-By: Claude Opus 5.5 --- .changeset/hover-card-shared-surface.md | 3 ++ .../docs/(kit)/components/hover-card.mdx | 9 +++- .../docs/css/components/hover-card.mdx | 3 +- apps/docs/content/docs/design/patterns.mdx | 2 +- packages/kit/DESIGN.md | 2 +- packages/kit/api/kit.api.md | 13 +++++- .../src/components/HoverCard/HoverCard.tsx | 19 ++++++-- .../components/HoverCard/HoverCardHost.tsx | 33 +++++++++++++- packages/kit/test/hover-card-shared.test.tsx | 30 +++++++++++++ .../src/stories/HoverCard.stories.tsx | 44 ++++++++++++++++++- .../css/components/HoverCard/HoverCard.css | 17 +++++++ 11 files changed, 162 insertions(+), 13 deletions(-) diff --git a/.changeset/hover-card-shared-surface.md b/.changeset/hover-card-shared-surface.md index a69f97a9..313a3b14 100644 --- a/.changeset/hover-card-shared-surface.md +++ b/.changeset/hover-card-shared-surface.md @@ -1,5 +1,6 @@ --- "@codeui/kit": minor +"@codeui/styles": minor --- Hover cards share one card and move it between triggers. @@ -9,3 +10,5 @@ Hover cards share one card and move it between triggers. - `HoverCardContent` is no longer polymorphic. Its `class`, `classes`, `style`, `ref`, `mount` and dismiss handlers go on the card; other attributes and event handlers go on a `display: contents` element around the children. - `HoverCard` drops the Kobalte root options it never used (`id`). The trigger renders without a Kobalte popover anchor and still sets `data-expanded` and `data-closed`. - Overlays opened by hover tell pointer from keyboard more reliably: the input tracker also records `pointerover`, which the browser fires before the `pointermove` that crosses into an element. +- A hover card opened from inside another card's content gets a surface of its own. The outer card stays open while the pointer is on the inner card and until it closes, and a press on the inner card does not close it. +- An `a` trigger (alone or `as={Link}`) has a dotted underline in the hint tone (`--cui-hovercard-trigger-decoration-color`) that takes the text colour on hover and while the card is open. diff --git a/apps/docs/content/docs/(kit)/components/hover-card.mdx b/apps/docs/content/docs/(kit)/components/hover-card.mdx index 738ba061..2d1d7965 100644 --- a/apps/docs/content/docs/(kit)/components/hover-card.mdx +++ b/apps/docs/content/docs/(kit)/components/hover-card.mdx @@ -64,7 +64,11 @@ All the hover cards of a page share one card. When the pointer or keyboard focus - When focus moves from the keyboard, the card swaps its content in place, with no motion. - With reduced motion, the card stays in place and only the new content fades in. -Because the card is shared, only one hover card is open at a time. A hover card inside another hover card, or one that must stay open next to another, needs its own surface: put it in a `HoverCardGroup` or pass `shared={false}`. +Because the card is shared, only one hover card of the page is open at a time. A card that must stay open next to another needs its own surface: put it in a `HoverCardGroup` or pass `shared={false}`. + +### Nested cards + +A hover card inside the content of another one gets a surface of its own, without a group. Both cards stay open: the outer card waits while the pointer is on the inner card and until the inner card closes. A press on the inner card does not close the outer one. Escape closes the inner card first. ### Groups @@ -120,6 +124,8 @@ Inherited from Kobalte's [popover](https://kobalte.dev/docs/core/components/popo Renders an `a`. Give it an `href`, or render another focusable element with `as`, so keyboard users can reach it. An `a` without `href` cannot take focus. +A trigger that renders an `a`, alone or through `as={Link}`, has a dotted underline in the hint tone, so it reads as something to hover inside running text. The underline takes the text colour on hover and while the card is open. A trigger rendered as a button or a row keeps its own look. + ### `HoverCardContent` Renders its children into the shared card, which is portaled to `document.body` and placed next to the trigger. While this card is the one shown, its `class`, `classes`, `style`, `ref`, `mount` and dismiss handlers go on the card. Any other attribute or event handler, such as `id`, `aria-hidden` or `onPointerEnter`, goes on a `display: contents` element around the children. @@ -172,6 +178,7 @@ The trigger renders on the server. The card renders on the client, and only whil | Variable | Default | Used for | | --- | --- | --- | +| `--cui-hovercard-trigger-decoration-color` | `--cui-text-hint` | Dotted underline of an `a` trigger, before hover | | `--cui-hovercard-content-background` | `--cui-surface-dialog` | Fill | | `--cui-hovercard-content-box-shadow` | `--cui-shadow-dialog` | Shadow, and the 1px ring in dark mode | | `--cui-hovercard-content-radius` | `--cui-radius-card` | Radius (16px) | diff --git a/apps/docs/content/docs/css/components/hover-card.mdx b/apps/docs/content/docs/css/components/hover-card.mdx index 0111308c..85a530cf 100644 --- a/apps/docs/content/docs/css/components/hover-card.mdx +++ b/apps/docs/content/docs/css/components/hover-card.mdx @@ -15,7 +15,7 @@ The demo renders the open card in normal flow, under its trigger. On a page, the | Part | Element | Class | `data-cui` | | --- | --- | --- | --- | -| Trigger | `a` with an `href` | none | `hovercard-trigger` | +| Trigger | `a` with an `href`. It gets a dotted underline in the hint tone | none | `hovercard-trigger` | | Content | `div` | `cui-hovercard-content` | `hovercard-content` | | List | `ul` with an `aria-label` | `cui-hovercard-list` | `hovercard-list` | | Entry | `li` | `cui-hovercard-item` | `hovercard-item` | @@ -25,6 +25,7 @@ The demo renders the open card in normal flow, under its trigger. On a page, the | Attribute | Values | Default | | --- | --- | --- | +| `data-expanded` on the trigger | Presence, while the card is open. The dotted underline takes the text colour | Off | | `data-expanded` on the content | Presence | Off | | `data-motion` on the content | `none` | None | diff --git a/apps/docs/content/docs/design/patterns.mdx b/apps/docs/content/docs/design/patterns.mdx index c9eba246..670686e7 100644 --- a/apps/docs/content/docs/design/patterns.mdx +++ b/apps/docs/content/docs/design/patterns.mdx @@ -71,7 +71,7 @@ A picker opens over the panel that holds it, anchored to its row. It does not pu A dialog is for settings and for decisions the user must make before continuing, such as reviewing detected secrets before an export. It is not for asking "are you sure?" about something that can be undone. -A tooltip is one line that names one thing. A description, or several facts about a row, goes in a hover card beside its trigger, on the right unless there is no room, wrapped at about 20rem. It opens on click too, so touch works, and everything in it is reachable another way. The `title` attribute is never used: it is slow, unstyled, and invisible to touch and keyboard. Use the kit [`HoverCard`](/docs/components/hover-card): it opens on hover, focus and click, sits on the right by default, and follows Pop. Moving to the next trigger while a card is open moves that card instead of opening a second one: it slides to the new trigger and resizes to the new content. +A tooltip is one line that names one thing. A description, or several facts about a row, goes in a hover card beside its trigger, on the right unless there is no room, wrapped at about 20rem. It opens on click too, so touch works, and everything in it is reachable another way. The `title` attribute is never used: it is slow, unstyled, and invisible to touch and keyboard. Use the kit [`HoverCard`](/docs/components/hover-card): it opens on hover, focus and click, sits on the right by default, and follows Pop. Moving to the next trigger while a card is open moves that card instead of opening a second one: it slides to the new trigger and resizes to the new content. A trigger in running text has a dotted underline in the hint tone, so it reads as something to hover. A list inside a menu or a hover card has one line per entry: state icon, identifier, title truncated. Nesting shows by indent, and a prefix that every entry shares is dropped. Two or more entries for the same action go in a submenu labelled with the count, so the menu does not fill up with "Open …" rows. A long list caps at about 24rem and scrolls on its own. In a hover card, build it with `HoverCardList` and `HoverCardItem`. diff --git a/packages/kit/DESIGN.md b/packages/kit/DESIGN.md index 1b02e0fe..cdb3d224 100644 --- a/packages/kit/DESIGN.md +++ b/packages/kit/DESIGN.md @@ -365,7 +365,7 @@ No border; field fill, radius 12, padding 12; a 68px preview well (radius 8) ove - A picker opens anchored to its row, over the panel that holds it: 360px, radius 16, padding 16. - A dialog is for settings and for blocking decisions, not for confirming something undoable. -- A tooltip is one line that names one thing. A description, or more than one fact, goes in a hover card beside its trigger, on the right unless there is no room, wrapped at about 20rem. It opens on click too, so touch works. Never use the `title` attribute. Everything in a hover card is reachable another way. Use the kit `HoverCard`: `right-start` by default, a click or tap opens it at once, Pop motion, and the floating surface. Moving to the next trigger while a card is open moves that card: it slides to the new trigger and resizes to the new content in 200ms ease-out, with no second pop. From the keyboard it swaps in place. Hover cards share one card per page; a `HoverCardGroup` gives a set of triggers their own. +- A tooltip is one line that names one thing. A description, or more than one fact, goes in a hover card beside its trigger, on the right unless there is no room, wrapped at about 20rem. It opens on click too, so touch works. Never use the `title` attribute. Everything in a hover card is reachable another way. Use the kit `HoverCard`: `right-start` by default, a click or tap opens it at once, Pop motion, and the floating surface. Moving to the next trigger while a card is open moves that card: it slides to the new trigger and resizes to the new content in 200ms ease-out, with no second pop. From the keyboard it swaps in place. Hover cards share one card per page; a `HoverCardGroup` gives a set of triggers their own. A text trigger has a dotted underline in the hint tone that takes the text colour on hover and while open. - A list in a menu or hover card has one line per entry: state icon, identifier, title truncated. Show nesting by indent, and drop a prefix every entry shares. Two or more entries for one action go in a submenu labelled with the count. A long list caps at about 24rem and scrolls on its own. In a hover card, use `HoverCardList` and `HoverCardItem`; the icon slot stays when an entry has no icon. diff --git a/packages/kit/api/kit.api.md b/packages/kit/api/kit.api.md index dc9ae07c..8fbba078 100644 --- a/packages/kit/api/kit.api.md +++ b/packages/kit/api/kit.api.md @@ -4121,7 +4121,8 @@ export type HoverCardContentProps = Omit, "st * placed beside the trigger (on the right unless there is no room), and never takes focus. * Its class, style, ref and dismiss handlers go on that surface while this card is the one * shown. Other attributes and event handlers go on a `display: contents` element that wraps - * the children inside it. + * the children inside it. Hover cards inside the content get a surface of their own, so the + * card stays open beside them. */ export declare function HoverCardContent(props: HoverCardContentProps): JSX.Element; export type HoverCardListProps = JSX.HTMLAttributes & { @@ -4244,6 +4245,16 @@ export type HoverCardGroupProps = ParentProps<{ * that card, and they never take over the surface of the cards outside the group. */ export declare function HoverCardGroup(props: HoverCardGroupProps): JSX.Element; +/** Makes `host` the surface of the hover cards below it, and renders that surface. */ +export declare function HoverCardHostProvider(props: ParentProps<{ + host: HoverCardHost; +}>): JSX.Element; +/** + * True when `target` is inside `element`, following portals back to where they were + * declared. A hover card opened from inside another card is portaled to the body, but + * Solid links its nodes to their declaration inside the outer card. + */ +export declare function withinPortal(target: EventTarget | null, element: Node | undefined): boolean; /** The popover the host places next to the active trigger. */ export declare function HoverCardSurface(props: { host: HoverCardHost; diff --git a/packages/kit/src/components/HoverCard/HoverCard.tsx b/packages/kit/src/components/HoverCard/HoverCard.tsx index 1fb82e1b..acd5cb4f 100644 --- a/packages/kit/src/components/HoverCard/HoverCard.tsx +++ b/packages/kit/src/components/HoverCard/HoverCard.tsx @@ -23,7 +23,10 @@ import { mergeClasses } from "../../utils/css"; import * as styles from "./HoverCard.css"; import { createHoverCardHost, + HoverCardHostProvider, HoverCardSurface, + withinPortal, + type HoverCardHost, positioningKeys, useHoverCardHost, type HoverCardDismissHandlers, @@ -68,6 +71,8 @@ type HoverCardController = { setSurface: (options: HoverCardSurfaceOptions | undefined) => void; slot: () => HTMLElement | undefined; contains: (target: EventTarget | null) => boolean; + /** The surface of the hover cards opened from inside this card's content. */ + nested: HoverCardHost; }; const HoverCardContext = createContext(); @@ -174,10 +179,11 @@ export function HoverCard(props: ParentProps) { if (state) host.show(entry); else setOpen(true); }; + const nested = createHoverCardHost(); const contains = (target: EventTarget | null) => target instanceof Node && Boolean( - trigger()?.contains(target) || (isOpen() && host.surface()?.contains(target)), + trigger()?.contains(target) || (isOpen() && withinPortal(target, host.surface())), ); const controller: HoverCardController = { @@ -203,6 +209,7 @@ export function HoverCard(props: ParentProps) { setSurface, slot: () => host.slotFor(entry), contains, + nested, }; if (ownSurface) host.attach(entry); @@ -217,7 +224,8 @@ export function HoverCard(props: ParentProps) { if (isServer || !elements) return; const onPointerMove = (event: PointerEvent) => { if (event.pointerType === "touch") return; - if (contains(event.target)) return cancelClose(); + // A card opened from inside this one keeps it open until that card closes. + if (contains(event.target) || nested.open()) return cancelClose(); const { trigger, content } = elements; if ( !props.ignoreSafeArea && @@ -346,7 +354,8 @@ function applyRef(ref: unknown, element: HTMLElement) { * placed beside the trigger (on the right unless there is no room), and never takes focus. * Its class, style, ref and dismiss handlers go on that surface while this card is the one * shown. Other attributes and event handlers go on a `display: contents` element that wraps - * the children inside it. + * the children inside it. Hover cards inside the content get a surface of their own, so the + * card stays open beside them. */ export function HoverCardContent(props: HoverCardContentProps) { const card = useHoverCard(); @@ -388,7 +397,9 @@ export function HoverCardContent(props: HoverCardContentProps) { {slot => (
- {props.children} + + {props.children} +
)} diff --git a/packages/kit/src/components/HoverCard/HoverCardHost.tsx b/packages/kit/src/components/HoverCard/HoverCardHost.tsx index 94604bb5..8338818f 100644 --- a/packages/kit/src/components/HoverCard/HoverCardHost.tsx +++ b/packages/kit/src/components/HoverCard/HoverCardHost.tsx @@ -275,6 +275,12 @@ export function HoverCardGroup(props: HoverCardGroupProps) { return props.skipDelayDuration; }, }); + return {props.children}; +} + +/** Makes `host` the surface of the hover cards below it, and renders that surface. */ +export function HoverCardHostProvider(props: ParentProps<{ host: HoverCardHost }>) { + const host = untrack(() => props.host); return ( {props.children} @@ -283,6 +289,26 @@ export function HoverCardGroup(props: HoverCardGroupProps) { ); } +/** + * True when `target` is inside `element`, following portals back to where they were + * declared. A hover card opened from inside another card is portaled to the body, but + * Solid links its nodes to their declaration inside the outer card. + */ +export function withinPortal(target: EventTarget | null, element: Node | undefined) { + if (!element) return false; + for (let node = target; node instanceof Node; ) { + if (node === element) return true; + const host = "_$host" in node ? node._$host : undefined; + node = + host instanceof Node + ? host + : node instanceof ShadowRoot + ? node.host + : node.parentNode; + } + return false; +} + function positioningOf(entry: Accessor) { const positioning = {} as Required; for (const key of positioningKeys) @@ -355,7 +381,9 @@ function SurfaceContent(props: { host: HoverCardHost }) { onPointerDownOutside={(event: PointerDownOutsideEvent) => { options()?.onPointerDownOutside?.(event); // A press on a trigger is a click that keeps the card open or moves it there. - if (onTrigger(event.target)) event.preventDefault(); + // A press on a card opened from inside this one is inside it. + if (onTrigger(event.target) || withinPortal(event.target, host.surface())) + event.preventDefault(); }} onFocusOutside={( event: Parameters>[0], @@ -363,7 +391,8 @@ function SurfaceContent(props: { host: HoverCardHost }) { options()?.onFocusOutside?.(event); // Focus on another trigger moves the card there. Leaving the previous // trigger closes it through its blur handler and closeDelay instead. - if (onTrigger(event.target)) event.preventDefault(); + if (onTrigger(event.target) || withinPortal(event.target, host.surface())) + event.preventDefault(); }} onInteractOutside={( event: Parameters< diff --git a/packages/kit/test/hover-card-shared.test.tsx b/packages/kit/test/hover-card-shared.test.tsx index 20573286..3d65dc29 100644 --- a/packages/kit/test/hover-card-shared.test.tsx +++ b/packages/kit/test/hover-card-shared.test.tsx @@ -194,3 +194,33 @@ it("closes the page card when the open HoverCard unmounts", async () => { setShown(false); await waitFor(() => expect(cards()).toHaveLength(0), { timeout: 200 }); }); + +it("keeps a card open beside a card opened from inside it", async () => { + render(() => ( + + Outer + + + Inner + Inner details + + + + )); + hover(screen.getByRole("link", { name: "Outer" })); + await waitFor(() => expect(cards()).toHaveLength(1)); + const outer = cards()[0]; + hover(await screen.findByRole("link", { name: "Inner" })); + await waitFor(() => expect(cards()).toHaveLength(2)); + const inner = cards().find(card => card !== outer)!; + expect(inner).toHaveTextContent("Inner details"); + expect(outer).toHaveTextContent("Inner"); + fireEvent.pointerMove(inner, { pointerType: "mouse" }); + await sleep(300); + expect(cards()).toEqual([outer, inner]); + fireEvent.pointerDown(inner, { pointerType: "mouse" }); + await sleep(50); + expect(cards()).toHaveLength(2); + press("Escape"); + await waitFor(() => expect(cards()).toEqual([outer])); +}); diff --git a/packages/storybook/src/stories/HoverCard.stories.tsx b/packages/storybook/src/stories/HoverCard.stories.tsx index 5b581c2e..11d17452 100644 --- a/packages/storybook/src/stories/HoverCard.stories.tsx +++ b/packages/storybook/src/stories/HoverCard.stories.tsx @@ -182,7 +182,11 @@ export const EdgePlacement: Story = { }; const threads = [ - { id: "flaky", title: "Fix flaky hydration test", meta: "Codex · 2 hours ago · 3 subagents" }, + { + id: "flaky", + title: "Fix flaky hydration test", + meta: "Codex · 2 hours ago · 3 subagents", + }, { id: "popover", title: "Port Popover to Solid 2", meta: "Claude · yesterday" }, { id: "docs", @@ -194,7 +198,9 @@ const threads = [ ]; const ThreadRows = () => ( -
+
{thread => ( @@ -243,3 +249,37 @@ export const Groups: Story = {
), }; + +export const Nested: Story = { + name: "Card inside a card", + args: {}, + render: () => ( +
+ + + Fix flaky hydration test + + + + Fix flaky hydration test + + + Opened by{" "} + + Codex + + + Codex + + + gpt-5.5 · 3 threads running + + + {" "} + 2 hours ago. + + + +
+ ), +}; diff --git a/packages/styles/css/components/HoverCard/HoverCard.css b/packages/styles/css/components/HoverCard/HoverCard.css index f5d14870..13a42f29 100644 --- a/packages/styles/css/components/HoverCard/HoverCard.css +++ b/packages/styles/css/components/HoverCard/HoverCard.css @@ -37,6 +37,23 @@ .cui-hovercard-content[data-motion=none], .cui-hovercard-content[data-motion=none][data-expanded] { animation: none; } + :where(a[data-cui="hovercard-trigger"]) { + --cui-hovercard-trigger-decoration-color: var(--cui-text-hint); + text-decoration-line: underline; + text-decoration-style: dotted; + text-decoration-thickness: 1px; + text-underline-offset: 0.2em; + text-decoration-color: var(--cui-hovercard-trigger-decoration-color); + transition: text-decoration-color var(--cui-motion-duration-fast) ease; + } + :where(a[data-cui="hovercard-trigger"])[data-expanded] { + text-decoration-color: currentColor; + } + @media (hover: hover) and (pointer: fine) { + :where(a[data-cui="hovercard-trigger"]):hover { + text-decoration-color: currentColor; + } + } .cui-hovercard-list { list-style: none; margin: 0 calc(var(--cui-space-2) * -1);