From 902bf616a0cc590d3f89f233f0c4e00072e549f0 Mon Sep 17 00:00:00 2001
From: Daniel Antoni <135056236+d4nielantoni@users.noreply.github.com>
Date: Sun, 15 Nov 2026 22:11:28 -0300
Subject: [PATCH] fix(gallery): open style cards from the keyboard and stop
nested clicks (#578)
The style card was a
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
; 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.
---
gallery/components/CodeSnippet.tsx | 2 +-
gallery/components/StyleCard.tsx | 15 ++++--
gallery/components/StyleCardTitle.tsx | 28 ++++++++++
gallery/components/StyleDetailModal.tsx | 52 ++++++++++++++++--
gallery/components/style-card.test.tsx | 72 +++++++++++++++++++++++++
gallery/lib/nestedControl.ts | 48 +++++++++++++++++
gallery/package.json | 2 +-
gallery/tsconfig.test.json | 5 +-
8 files changed, 213 insertions(+), 11 deletions(-)
create mode 100644 gallery/components/StyleCardTitle.tsx
create mode 100644 gallery/components/style-card.test.tsx
create mode 100644 gallery/lib/nestedControl.ts
diff --git a/gallery/components/CodeSnippet.tsx b/gallery/components/CodeSnippet.tsx
index 38b4cdc..66684f2 100644
--- a/gallery/components/CodeSnippet.tsx
+++ b/gallery/components/CodeSnippet.tsx
@@ -32,7 +32,7 @@ export function CodeSnippet({ code, label }: CodeSnippetProps) {
{copied ? (
diff --git a/gallery/components/StyleCard.tsx b/gallery/components/StyleCard.tsx
index c134fc2..ae62dfc 100644
--- a/gallery/components/StyleCard.tsx
+++ b/gallery/components/StyleCard.tsx
@@ -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 (
onSelect?.(style)}
+ onClick={(e) => {
+ if (isNestedControlClick(e.target, e.currentTarget)) return;
+ if (hasTextSelectionIn(window.getSelection(), e.currentTarget)) return;
+ onSelect?.(style);
+ }}
>
{/* Header */}
-
- {style.styleCategory}
-
+
onSelect(style) : undefined}
+ />
{style.type}
diff --git a/gallery/components/StyleCardTitle.tsx b/gallery/components/StyleCardTitle.tsx
new file mode 100644
index 0000000..d1ac681
--- /dev/null
+++ b/gallery/components/StyleCardTitle.tsx
@@ -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 {name} ;
+
+ return (
+
+
+ {name}
+
+
+ );
+}
diff --git a/gallery/components/StyleDetailModal.tsx b/gallery/components/StyleDetailModal.tsx
index 7f7124e..f8fe680 100644
--- a/gallery/components/StyleDetailModal.tsx
+++ b/gallery/components/StyleDetailModal.tsx
@@ -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(null);
+ const closeButtonRef = useRef(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(
+ '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 */}
e.stopPropagation()}
>
{/* Header */}
@@ -85,7 +126,10 @@ export function StyleDetailModal({ style, onClose }: StyleDetailModalProps) {
Close
-
+
{style.styleCategory}
{/* Spacer for centering */}
diff --git a/gallery/components/style-card.test.tsx b/gallery/components/style-card.test.tsx
new file mode 100644
index 0000000..a79a167
--- /dev/null
+++ b/gallery/components/style-card.test.tsx
@@ -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;
+}
+const card = cardContaining(controlNode);
+
+test("style card title is a keyboard-reachable button that opens the detail dialog", () => {
+ const markup = renderToStaticMarkup(
+ undefined} />,
+ );
+ const button = markup.match(/^]*>(]*>)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( );
+
+ assert.match(markup, /^]*>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);
+});
diff --git a/gallery/lib/nestedControl.ts b/gallery/lib/nestedControl.ts
new file mode 100644
index 0000000..07e04b2
--- /dev/null
+++ b/gallery/lib/nestedControl.ts
@@ -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,
+): 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 | null,
+ card: Pick,
+): boolean {
+ return (
+ selection !== null &&
+ !selection.isCollapsed &&
+ card.contains(selection.anchorNode)
+ );
+}
diff --git a/gallery/package.json b/gallery/package.json
index 543d501..b234c35 100644
--- a/gallery/package.json
+++ b/gallery/package.json
@@ -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": {
diff --git a/gallery/tsconfig.test.json b/gallery/tsconfig.test.json
index 9811d55..af88742 100644
--- a/gallery/tsconfig.test.json
+++ b/gallery/tsconfig.test.json
@@ -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"
]
}