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 + + ); +} 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 */}
-

+

{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" ] }