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.
This commit is contained in:
Daniel Antoni 2026-11-15 22:11:28 -03:00 committed by GitHub
parent b6a79003ad
commit 902bf616a0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 213 additions and 11 deletions

View File

@ -32,7 +32,7 @@ export function CodeSnippet({ code, label }: CodeSnippetProps) {
</pre>
<button
onClick={handleCopy}
className="absolute top-2 right-2 p-1.5 rounded-md bg-gray-200/80 dark:bg-gray-700/80 text-gray-500 dark:text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity hover:bg-gray-300 dark:hover:bg-gray-600"
className="absolute top-2 right-2 p-1.5 rounded-md bg-gray-200/80 dark:bg-gray-700/80 text-gray-500 dark:text-gray-400 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity hover:bg-gray-300 dark:hover:bg-gray-600"
title="Copy to clipboard"
>
{copied ? (

View File

@ -1,6 +1,8 @@
"use client";
import { StyleData } from "@/lib/types";
import { hasTextSelectionIn, isNestedControlClick } from "@/lib/nestedControl";
import { StyleCardTitle } from "./StyleCardTitle";
import { StylePreview } from "./StylePreview";
import { ColorPalette } from "./ColorPalette";
import { MetadataBadges } from "./MetadataBadges";
@ -17,14 +19,19 @@ export function StyleCard({ style, onSelect }: StyleCardProps) {
return (
<div
className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden hover:shadow-lg dark:hover:shadow-gray-900/50 transition-shadow cursor-pointer"
onClick={() => onSelect?.(style)}
onClick={(e) => {
if (isNestedControlClick(e.target, e.currentTarget)) return;
if (hasTextSelectionIn(window.getSelection(), e.currentTarget)) return;
onSelect?.(style);
}}
>
{/* Header */}
<div className="px-4 pt-4 pb-2">
<div className="flex items-start justify-between gap-2">
<h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100 leading-tight">
{style.styleCategory}
</h3>
<StyleCardTitle
name={style.styleCategory}
onOpen={onSelect ? () => onSelect(style) : undefined}
/>
<div className="flex items-center gap-1.5 shrink-0">
<span className="text-[10px] px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400">
{style.type}

View File

@ -0,0 +1,28 @@
interface StyleCardTitleProps {
name: string;
onOpen?: () => void;
}
const TITLE_CLASS =
"text-sm font-semibold text-gray-900 dark:text-gray-100 leading-tight";
// The title is a real button so keyboard and screen reader users can open the
// detail modal; making the whole card a button would nest its other controls.
// The focus mark is an outline, not a ring: forced-colors mode drops the
// box-shadow a ring is drawn with.
export function StyleCardTitle({ name, onOpen }: StyleCardTitleProps) {
if (!onOpen) return <h3 className={TITLE_CLASS}>{name}</h3>;
return (
<h3 className={TITLE_CLASS}>
<button
type="button"
aria-haspopup="dialog"
onClick={onOpen}
className="text-left rounded focus:outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
>
{name}
</button>
</h3>
);
}

View File

@ -1,6 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import { useEffect, useId, useRef, useState } from "react";
import { useTheme } from "next-themes";
import { StyleData } from "@/lib/types";
import {
@ -25,10 +25,46 @@ export function StyleDetailModal({ style, onClose }: StyleDetailModalProps) {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
// ESC to close
const dialogRef = useRef<HTMLDivElement>(null);
const closeButtonRef = useRef<HTMLButtonElement>(null);
const titleId = useId();
// Move focus into the dialog on open and give it back on close to whatever
// had it before (the card title when opened from the keyboard), so
// keyboard users are not left behind the overlay.
useEffect(() => {
const opener = document.activeElement as HTMLElement | null;
closeButtonRef.current?.focus();
return () => {
if (opener?.isConnected) opener.focus({ preventScroll: true });
};
}, []);
// ESC to close; Tab and Shift+Tab wrap inside the dialog
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") onClose();
if (e.key === "Escape") {
onClose();
return;
}
if (e.key !== "Tab" || !dialogRef.current) return;
const focusable = Array.from(
dialogRef.current.querySelectorAll<HTMLElement>(
'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]'
)
).filter((el) => el.tabIndex >= 0);
if (focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
const active = document.activeElement;
const outside = !dialogRef.current.contains(active);
if (e.shiftKey && (active === first || outside)) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && (active === last || outside)) {
e.preventDefault();
first.focus();
}
}
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
@ -61,12 +97,17 @@ export function StyleDetailModal({ style, onClose }: StyleDetailModalProps) {
{/* Modal container */}
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
className="relative z-10 bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-[95vw] max-w-5xl max-h-[90vh] overflow-hidden flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-800 shrink-0">
<button
ref={closeButtonRef}
onClick={onClose}
className="flex items-center gap-1.5 text-sm text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
>
@ -85,7 +126,10 @@ export function StyleDetailModal({ style, onClose }: StyleDetailModalProps) {
</svg>
Close
</button>
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
<h2
id={titleId}
className="text-lg font-semibold text-gray-900 dark:text-gray-100"
>
{style.styleCategory}
</h2>
<div className="w-16" /> {/* Spacer for centering */}

View File

@ -0,0 +1,72 @@
import assert from "node:assert/strict";
import test from "node:test";
import { renderToStaticMarkup } from "react-dom/server";
import { hasTextSelectionIn, isNestedControlClick } from "../lib/nestedControl";
import { StyleCardTitle } from "./StyleCardTitle";
// Stands in for a DOM element: closest() returns a marker node when the
// element itself, or one of the ancestors listed in `path`, matches one of the
// selector's parts (a tag name such as "button" or an attribute selector such
// as '[role="switch"]').
const controlNode = {};
function targetInside(...path: string[]) {
return {
closest: (selector: string) => {
const parts = selector.split(",").map((part) => part.trim());
return path.some((node) => parts.includes(node)) ? controlNode : null;
},
} as unknown as EventTarget;
}
// A card that contains only the nodes it is given.
function cardContaining(...nodes: unknown[]) {
return { contains: (node: unknown) => nodes.includes(node) } as Pick<Node, "contains">;
}
const card = cardContaining(controlNode);
test("style card title is a keyboard-reachable button that opens the detail dialog", () => {
const markup = renderToStaticMarkup(
<StyleCardTitle name="Minimalism" onOpen={() => undefined} />,
);
const button = markup.match(/^<h3[^>]*>(<button[^>]*>)Minimalism<\/button><\/h3>$/);
assert.ok(button, `title is not a button inside the heading: ${markup}`);
assert.match(button[1], /\stype="button"/);
assert.match(button[1], /\saria-haspopup="dialog"/);
});
test("style card title is plain text when nothing can be opened", () => {
const markup = renderToStaticMarkup(<StyleCardTitle name="Minimalism" />);
assert.match(markup, /^<h3[^>]*>Minimalism<\/h3>$/);
});
test("clicks on the card's own controls do not open the detail dialog", () => {
assert.equal(isNestedControlClick(targetInside("button"), card), true);
assert.equal(isNestedControlClick(targetInside("svg", "button"), card), true);
assert.equal(isNestedControlClick(targetInside("input"), card), true);
assert.equal(isNestedControlClick(targetInside("span", "label"), card), true);
assert.equal(isNestedControlClick(targetInside("summary"), card), true);
assert.equal(isNestedControlClick(targetInside('[role="switch"]'), card), true);
assert.equal(isNestedControlClick(targetInside("div"), card), false);
assert.equal(isNestedControlClick(targetInside("pre", "div"), card), false);
assert.equal(isNestedControlClick(null, card), false);
assert.equal(isNestedControlClick({} as EventTarget, card), false);
});
test("a control wrapped around the whole card does not block opening it", () => {
assert.equal(isNestedControlClick(targetInside("div", "a"), cardContaining()), false);
});
test("a click that ends a text selection does not open the detail dialog", () => {
const inside = {} as Node;
const elsewhere = {} as Node;
const card = cardContaining(inside);
assert.equal(hasTextSelectionIn({ isCollapsed: false, anchorNode: inside }, card), true);
assert.equal(hasTextSelectionIn({ isCollapsed: true, anchorNode: inside }, card), false);
assert.equal(hasTextSelectionIn({ isCollapsed: false, anchorNode: elsewhere }, card), false);
assert.equal(hasTextSelectionIn(null, card), false);
});

View File

@ -0,0 +1,48 @@
// 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)
);
}

View File

@ -5,7 +5,7 @@
"scripts": {
"dev": "next dev",
"build": "next build",
"test": "tsc -p tsconfig.test.json && node --test .test-dist/lib/parseStyles.test.js .test-dist/components/metadata-badges.test.js",
"test": "tsc -p tsconfig.test.json && node --test .test-dist/lib/parseStyles.test.js .test-dist/components/metadata-badges.test.js .test-dist/components/style-card.test.js",
"start": "next start"
},
"dependencies": {

View File

@ -20,8 +20,11 @@
"lib/parseStyles.ts",
"lib/filterStyles.ts",
"lib/parseStyles.test.ts",
"lib/nestedControl.ts",
"components/MetadataBadges.tsx",
"components/FilterBar.tsx",
"components/metadata-badges.test.tsx"
"components/StyleCardTitle.tsx",
"components/metadata-badges.test.tsx",
"components/style-card.test.tsx"
]
}