ui-ux-pro-max-skill/gallery/lib/nestedControl.ts
Daniel Antoni 902bf616a0
fix(gallery): open style cards from the keyboard and stop nested clicks (#578)
The style card was a <div onClick> with no focusable control, so keyboard
and screen reader users could not open the detail modal (#573, item D1).
The card title is now a real <button aria-haspopup="dialog">; making the
whole card a button would nest its section toggles, copy buttons, color
swatches and checklist inside it. The focus mark is an outline, which
forced-colors mode keeps.

The detail modal now behaves as a dialog for those users: it has
role="dialog", aria-modal and its title as label, moves focus to Close on
open, keeps Tab and Shift+Tab inside, and returns focus to the element
that opened it when it closes.

The card's click handler also fired for every control inside it, so
expanding "CSS Code", copying a color or ticking a checklist item opened
the detail modal too, by mouse or keyboard. Clicks that start on a control
inside the card, or that end a text selection inside it, now leave the
modal closed; any other click on the card still opens it.

The code copy button was reachable with Tab but stayed at opacity 0 unless
hovered; it now shows while focused.
2026-11-16 08:11:28 +07:00

49 lines
1.5 KiB
TypeScript

// A style card holds its own controls (section toggles, copy buttons, color
// swatches, checklist items). A click on one of them must only do that
// control's job instead of bubbling up and opening the detail modal.
const NESTED_CONTROL_SELECTOR = [
"a",
"button",
"input",
"label",
"select",
"textarea",
"summary",
'[role="button"]',
'[role="checkbox"]',
'[role="switch"]',
'[role="link"]',
'[role="tab"]',
'[role="menuitem"]',
'[role="option"]',
"[contenteditable]",
'[tabindex]:not([tabindex="-1"])',
].join(", ");
// Duck-typed rather than `instanceof Element` so the gallery's DOM-free unit
// tests can exercise it. Only a control inside `card` counts, so a card that
// is itself wrapped in a link or label still opens.
export function isNestedControlClick(
target: EventTarget | null,
card: Pick<Node, "contains">,
): boolean {
const element = target as Element | null;
if (typeof element?.closest !== "function") return false;
const control = element.closest(NESTED_CONTROL_SELECTOR);
return control !== null && card.contains(control);
}
// A drag that selects text inside the card (for example in an open "CSS Code"
// section) ends in a click on the card; it should leave the selection alone.
// A selection elsewhere on the page does not block opening the card.
export function hasTextSelectionIn(
selection: Pick<Selection, "isCollapsed" | "anchorNode"> | null,
card: Pick<Node, "contains">,
): boolean {
return (
selection !== null &&
!selection.isCollapsed &&
card.contains(selection.anchorNode)
);
}