An open source design system that's fully customizable and agent ready
TypeScript
feat: a single-choice set of selectable cards is a radio group (lab SelectableCardGroup) (#8260)
Christopher Chedeau9136e28c781a
diff --git a/.changeset/lab-selectable-card-group-cli-discover.md b/.changeset/lab-selectable-card-group-cli-discover.mdnew file mode 100644index 0000000000..88f5cdf49d--- /dev/null+++ b/.changeset/lab-selectable-card-group-cli-discover.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[experimental] `astryx` discovery lists the lab's new `SelectableCardGroup`.++@vjeuxdiff --git a/.changeset/selectable-card-internal-input.md b/.changeset/selectable-card-internal-input.mdnew file mode 100644index 0000000000..260bff5282--- /dev/null+++ b/.changeset/selectable-card-internal-input.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: SelectableCard reads an internal input context that Lab's SelectableCardGroup uses to render its cards as a native radio group. SelectableCard's public props and behavior do not change.++@vjeuxdiff --git a/apps/storybook/stories/SelectableCardGroup.stories.tsx b/apps/storybook/stories/SelectableCardGroup.stories.tsxnew file mode 100644index 0000000000..2bad02a937--- /dev/null+++ b/apps/storybook/stories/SelectableCardGroup.stories.tsx@@ -0,0 +1,191 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {Text} from '@astryxdesign/core/Text';+import {VStack} from '@astryxdesign/core/Layout';+import {+ SelectableCardGroup,+ SelectableCardGroupItem,+} from '@astryxdesign/lab/SelectableCardGroup';++const meta: Meta<typeof SelectableCardGroup> = {+ title: 'Lab/SelectableCardGroup',+ component: SelectableCardGroup,+ tags: ['autodocs'],+ parameters: {+ docs: {+ description: {+ component:+ 'A set of selectable cards with the semantics of its selection. One choice is a radio group (one tab stop, arrow keys, "2 of 3" spoken); several are a group of checkboxes.',+ },+ },+ },+};++export default meta;+type Story = StoryObj<typeof SelectableCardGroup>;++const PLANS = [+ {id: 'basic', name: 'Basic', price: '$9/mo'},+ {id: 'pro', name: 'Pro', price: '$29/mo'},+ {id: 'team', name: 'Team', price: '$99/mo'},+];++function PlanContent({name, price}: {name: string; price: string}) {+ return (+ <VStack gap={1}>+ <Text type="body" weight="bold">+ {name}+ </Text>+ <Text type="supporting" color="secondary">+ {price}+ </Text>+ </VStack>+ );+}++export const SingleChoice: Story = {+ name: 'Single choice (radio group)',+ render: () => {+ const [plan, setPlan] = useState<string | null>('basic');+ return (+ <SelectableCardGroup+ label="Plan"+ description="Billed monthly"+ value={plan}+ onChange={setPlan}>+ {PLANS.map(p => (+ <SelectableCardGroupItem+ key={p.id}+ value={p.id}+ label={p.name}+ width={160}>+ <PlanContent name={p.name} price={p.price} />+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ );+ },+};++export const MultipleChoice: Story = {+ name: 'Multiple choice (checkboxes)',+ render: () => {+ const [addOns, setAddOns] = useState<string[]>(['pro']);+ return (+ <SelectableCardGroup+ label="Add-ons"+ selectionMode="multiple"+ value={addOns}+ onChange={setAddOns}>+ {PLANS.map(p => (+ <SelectableCardGroupItem+ key={p.id}+ value={p.id}+ label={p.name}+ width={160}>+ <PlanContent name={p.name} price={p.price} />+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ );+ },+};++export const Vertical: Story = {+ render: () => {+ const [plan, setPlan] = useState<string | null>(null);+ return (+ <SelectableCardGroup+ label="Plan"+ orientation="vertical"+ value={plan}+ onChange={setPlan}>+ {PLANS.map(p => (+ <SelectableCardGroupItem+ key={p.id}+ value={p.id}+ label={p.name}+ maxWidth={320}>+ <PlanContent name={p.name} price={p.price} />+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ );+ },+};++export const Disabled: Story = {+ render: () => (+ <SelectableCardGroup+ label="Plan"+ value="pro"+ isDisabled+ onChange={() => {}}>+ {PLANS.map(p => (+ <SelectableCardGroupItem+ key={p.id}+ value={p.id}+ label={p.name}+ width={160}>+ <PlanContent name={p.name} price={p.price} />+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ ),+};++export const TwoFormsSharedName: Story = {+ name: 'Two forms, one htmlName',+ render: () => {+ const [first, setFirst] = useState<string | null>('pro');+ const [second, setSecond] = useState<string | null>('team');+ return (+ <VStack gap={4}>+ <form aria-label="First subscription">+ <SelectableCardGroup+ label="First plan"+ htmlName="plan"+ value={first}+ onChange={setFirst}>+ {PLANS.map(p => (+ <SelectableCardGroupItem+ key={p.id}+ value={p.id}+ label={`First ${p.name}`}+ width={160}>+ <PlanContent name={p.name} price={p.price} />+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ </form>+ <form aria-label="Second subscription">+ <SelectableCardGroup+ label="Second plan"+ htmlName="plan"+ value={second}+ onChange={setSecond}>+ {PLANS.map(p => (+ <SelectableCardGroupItem+ key={p.id}+ value={p.id}+ label={`Second ${p.name}`}+ width={160}>+ <PlanContent name={p.name} price={p.price} />+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ </form>+ </VStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Two single-choice groups in separate forms that share an htmlName stay separate radio groups, and each form submits its own choice.',+ },+ },+ },+};diff --git a/docs/specs/components/SelectableCard/SelectableCard.spec.md b/docs/specs/components/SelectableCard/SelectableCard.spec.mdindex ea4e1ccfbf..a1fabcafa0 100644--- a/docs/specs/components/SelectableCard/SelectableCard.spec.md+++ b/docs/specs/components/SelectableCard/SelectableCard.spec.md@@ -117,6 +117,10 @@ Consumer migration instructions belong in consumer docs and release notes.the delegated focus indicator, and the disabled treatment.- The `selectable-card` target and the public `--selectable-card-ring-color`variable.+- Internal note: through an internal channel, Lab's SelectableCardGroup can+ render the card's hidden input as a radio in a native radio group. No public+ prop exposes this; single-select stays outside the public contract until the+ group is promoted to Core.**Does not own / non-goals**diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex a7eb435b9c..5299341137 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -642,6 +642,11 @@"path": "components/lab/schedule","aliases": []},+ {+ "name": "component-lab-selectable-card-group",+ "path": "components/lab/selectable-card-group",+ "aliases": []+ },{"name": "component-lab-stat","path": "components/lab/stat",diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.jsonindex 15bd9a9b23..0c0c37c09e 100644--- a/packages/cli/assets/discover/official-packages.json+++ b/packages/cli/assets/discover/official-packages.json@@ -160,6 +160,10 @@"kind": "component","name": "Schedule"},+ {+ "kind": "component",+ "name": "SelectableCardGroup"+ },{"kind": "component","name": "Stat"diff --git a/packages/core/package.json b/packages/core/package.jsonindex 914c879912..d3da118020 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -838,6 +838,11 @@"source": "./src/internal/touch-sheet.ts","types": "./dist/internal/touch-sheet.d.ts","default": "./dist/internal/touch-sheet.js"+ },+ "./internal/selectable-card": {+ "source": "./src/internal/selectable-card.ts",+ "types": "./dist/internal/selectable-card.d.ts",+ "default": "./dist/internal/selectable-card.js"}},"files": [diff --git a/packages/core/src/SelectableCard/SelectableCard.tsx b/packages/core/src/SelectableCard/SelectableCard.tsxindex 4b68921405..f4c2d262b7 100644--- a/packages/core/src/SelectableCard/SelectableCard.tsx+++ b/packages/core/src/SelectableCard/SelectableCard.tsx@@ -23,6 +23,8 @@* A hidden <input type="checkbox"> inside the card provides the accessible* role, label, and checked state — the card surface itself has no role/tabIndex.* Space toggles it natively; Enter is wired up as an additional toggle key.+ * Inside a single-choice group (Lab's SelectableCardGroup, through an internal+ * context) the input is a radio: the card selects and never deselects itself.** For static display, use Card.* For navigation or action cards, use ClickableCard.@@ -34,13 +36,14 @@ import {type KeyboardEvent,useRef,useCallback,+ use,type Ref,} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';import type {Elevation, SizeValue, SpacingStep} from '../utils/types';-import {mergeProps} from '../utils';+import {isImeKeyEvent, mergeProps} from '../utils';import {Card} from '../Card/Card';import type {CardVariant} from '../Card/Card';import {useClickableContainer} from '../hooks/useClickableContainer';@@ -52,6 +55,7 @@ import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {usePressFeedback} from '../hooks/usePressFeedback';import {useMergedRefs} from '../hooks/useMergedRefs';+import {SelectableCardInputContext} from './selectableCardInput';// =============================================================================// Styles — selection + interaction; Card handles the rest// =============================================================================@@ -412,20 +416,34 @@ export function SelectableCard({const containerRef = useRef<HTMLDivElement | null>(null);const interactiveRef = useRef<HTMLInputElement | null>(null);+ // A group can make the input a radio. A radio only selects: a native radio+ // stays checked when it is clicked again.+ const groupInput = use(SelectableCardInputContext);+ const isRadio = groupInput?.type === 'radio';+ const requestChange = useCallback(() => {+ if (!isRadio) {+ onChange(!isSelected);+ } else if (!isSelected) {+ onChange(true);+ }+ }, [isRadio, isSelected, onChange]);+const handleClick = useCallback((_event: MouseEvent<HTMLElement>) => {if (!isDisabled) {- onChange(!isSelected);+ requestChange();}},- [isDisabled, isSelected, onChange],+ [isDisabled, requestChange],);- // The focusable control is a native checkbox, which toggles on Space but- // ignores Enter. Add Enter as an extra toggle key; Space keeps its native- // handling, so we deliberately do not toggle on Space here (would double).+ // A native checkbox or radio reacts to Space but not to Enter. This handler+ // adds Enter. Space is not handled here, because it would act twice.const handleKeyDown = useCallback((event: KeyboardEvent<HTMLInputElement>) => {+ if (isImeKeyEvent(event.nativeEvent)) {+ return;+ }if (isDisabled) {if (event.key === ' ' || event.key === 'Enter') {event.preventDefault();@@ -434,10 +452,10 @@ export function SelectableCard({}if (event.key === 'Enter') {event.preventDefault();- onChange(!isSelected);+ requestChange();}},- [isDisabled, isSelected, onChange],+ [isDisabled, requestChange],);const {onClick, onMouseUp} = useClickableContainer({@@ -523,7 +541,18 @@ export function SelectableCard({}><inputref={interactiveRef}- type="checkbox"+ type={isRadio ? 'radio' : 'checkbox'}+ name={groupInput?.name}+ value={groupInput?.value}+ // Radios group by name and form owner, so every radio card leaves+ // the form together and the group stays one tab stop. The group+ // submits its choice itself. A disabled checkbox card submits+ // nothing, so it leaves the form too.+ form={+ groupInput != null && (groupInput.type === 'radio' || isDisabled)+ ? ''+ : undefined+ }checked={isSelected}aria-label={label}aria-disabled={isDisabled ? 'true' : undefined}@@ -531,7 +560,7 @@ export function SelectableCard({if (isDisabled) {return;}- onChange(!isSelected);+ requestChange();}}onKeyDown={handleKeyDown}{...stylex.props(styles.srOnly)}diff --git a/packages/core/src/SelectableCard/SelectableCardRadio.test.tsx b/packages/core/src/SelectableCard/SelectableCardRadio.test.tsxnew file mode 100644index 0000000000..3e82619818--- /dev/null+++ b/packages/core/src/SelectableCard/SelectableCardRadio.test.tsx@@ -0,0 +1,137 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SelectableCardRadio.test.tsx+ * @input Uses SelectableCard, its internal input context, and Testing Library+ * @output Tests for SelectableCard's radio input+ * @position A card a group renders as a radio (through the internal+ * SelectableCardInputContext) is one choice of a set: a native radio in the+ * set's named group that selects and never deselects itself.+ */++import {useMemo, useState} from 'react';+import {describe, it, expect, vi} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {SelectableCard, type SelectableCardProps} from './SelectableCard';+import {SelectableCardInputContext} from './selectableCardInput';++/** A card the way a single-choice group renders it. */+function RadioCard({value, ...props}: SelectableCardProps & {value: string}) {+ const input = useMemo(+ () => ({+ type: 'radio' as const,+ name: 'plan',+ value,+ }),+ [value],+ );+ return (+ <SelectableCardInputContext value={input}>+ <SelectableCard {...props} />+ </SelectableCardInputContext>+ );+}++function Plans({onChange}: {onChange?: (value: string) => void}) {+ const [value, setValue] = useState('basic');+ return (+ <div role="radiogroup" aria-label="Plan">+ {['basic', 'pro', 'team'].map(plan => (+ <RadioCard+ key={plan}+ value={plan}+ label={plan}+ isSelected={value === plan}+ onChange={() => {+ setValue(plan);+ onChange?.(plan);+ }}>+ {plan}+ </RadioCard>+ ))}+ </div>+ );+}++describe('SelectableCard as a group radio', () => {+ it('renders a native radio in the named group', () => {+ render(<Plans />);+ const radios = screen.getAllByRole('radio');+ expect(radios).toHaveLength(3);+ for (const radio of radios) {+ expect(radio).toHaveAttribute('type', 'radio');+ expect(radio).toHaveAttribute('name', 'plan');+ }+ // A form submits the chosen card's value, not "on".+ expect(screen.getByRole('radio', {name: 'pro'})).toHaveAttribute(+ 'value',+ 'pro',+ );+ expect(screen.getByRole('radio', {name: 'basic'})).toBeChecked();+ expect(screen.queryByRole('checkbox')).toBeNull();+ });++ it('selects the clicked card and unchecks the others', () => {+ const onChange = vi.fn();+ render(<Plans onChange={onChange} />);+ fireEvent.click(screen.getByText('pro'));+ expect(onChange).toHaveBeenCalledWith('pro');+ expect(screen.getByRole('radio', {name: 'pro'})).toBeChecked();+ expect(screen.getByRole('radio', {name: 'basic'})).not.toBeChecked();+ });++ it('never deselects itself: a click or Enter on the selected card does nothing', () => {+ const onChange = vi.fn();+ render(+ <RadioCard value="basic" label="Basic" isSelected onChange={onChange}>+ Basic+ </RadioCard>,+ );+ fireEvent.click(screen.getByText('Basic'));+ fireEvent.keyDown(screen.getByRole('radio'), {key: 'Enter'});+ expect(onChange).not.toHaveBeenCalled();+ });++ it('selects on Enter when unselected', () => {+ const onChange = vi.fn();+ render(+ <RadioCard value="pro" label="Pro" isSelected={false} onChange={onChange}>+ Pro+ </RadioCard>,+ );+ fireEvent.keyDown(screen.getByRole('radio'), {key: 'Enter'});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(true);+ });++ it('a disabled radio card stays focusable and does not select', () => {+ const onChange = vi.fn();+ render(+ <RadioCard+ value="team"+ label="Team"+ isSelected={false}+ isDisabled+ onChange={onChange}>+ Team+ </RadioCard>,+ );+ const radio = screen.getByRole('radio');+ expect(radio).toHaveAttribute('aria-disabled', 'true');+ expect(radio).not.toBeDisabled();+ // Every radio card leaves the form, so the group stays one tab stop.+ expect(radio).toHaveAttribute('form', '');+ fireEvent.click(screen.getByText('Team'));+ fireEvent.keyDown(radio, {key: 'Enter'});+ expect(onChange).not.toHaveBeenCalled();+ });++ it('keeps the checkbox without a group', () => {+ render(+ <SelectableCard label="A" isSelected={false} onChange={() => {}}>+ A+ </SelectableCard>,+ );+ expect(screen.getByRole('checkbox')).toHaveAttribute('type', 'checkbox');+ });+});diff --git a/packages/core/src/SelectableCard/selectableCardInput.ts b/packages/core/src/SelectableCard/selectableCardInput.tsnew file mode 100644index 0000000000..090e8377bc--- /dev/null+++ b/packages/core/src/SelectableCard/selectableCardInput.ts@@ -0,0 +1,30 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file selectableCardInput.ts+ * @input A card group's choice of native input for each card it renders+ * @output SelectableCardInputContext: the input type, name and value a group+ * gives one SelectableCard+ * @position Internal: Lab's SelectableCardGroup provides it through+ * `@astryxdesign/core/internal/selectable-card`. It is not public API, so+ * SelectableCard's public props do not change.+ */++import {createContext} from 'react';++/** The native input a group gives one card. */+export interface SelectableCardInput {+ /** `radio` makes the card one choice of a single-choice set. */+ readonly type: 'checkbox' | 'radio';+ /** The input's `name`. Radios that share it form one native group. */+ readonly name: string;+ /** The input's `value`. A checkbox card submits it when it is selected. */+ readonly value: string;+}++/** Without a provider, a card renders its own checkbox. */+export const SelectableCardInputContext =+ createContext<SelectableCardInput | null>(null);+SelectableCardInputContext.displayName = 'SelectableCardInputContext';diff --git a/packages/core/src/internal/selectable-card.ts b/packages/core/src/internal/selectable-card.tsnew file mode 100644index 0000000000..90659b7fa3--- /dev/null+++ b/packages/core/src/internal/selectable-card.ts@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file selectable-card.ts+ * @input SelectableCard's internal input context, the Field input styling+ * rule and the aria id joiner+ * @output `@astryxdesign/core/internal/selectable-card`:+ * SelectableCardInputContext, useFieldInputStyling and joinAriaIDs,+ * re-exported by name+ * for Lab's SelectableCardGroup+ * @position An internal entry reserved for Astryx's own packages:+ * undocumented, outside the public API and its compatibility promise,+ * versioned in lockstep with Core, and allowed only in Core and Lab by the+ * `@astryx/no-core-internal-import` lint rule. Core components import the+ * same modules by relative path. Named re-exports only.+ *+ * SYNC: When modified, update scripts/sync-exports.js.+ */+export {SelectableCardInputContext} from '../SelectableCard/selectableCardInput';+export type {SelectableCardInput} from '../SelectableCard/selectableCardInput';+export {useFieldInputStyling} from '../Field/fieldParts';+export {joinAriaIDs} from '../utils/inputAria';diff --git a/packages/lab/src/SelectableCardGroup/SelectableCardGroup.doc.mjs b/packages/lab/src/SelectableCardGroup/SelectableCardGroup.doc.mjsnew file mode 100644index 0000000000..00e02166a3--- /dev/null+++ b/packages/lab/src/SelectableCardGroup/SelectableCardGroup.doc.mjs@@ -0,0 +1,262 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */+export const docs = {+ name: 'SelectableCardGroup',+ displayName: 'Selectable Card Group',+ category: 'Form Controls',+ keywords: [+ 'card',+ 'selectable',+ 'group',+ 'radio',+ 'radiogroup',+ 'checkbox',+ 'single choice',+ 'multiple choice',+ 'plan picker',+ 'selection',+ ],+ description:+ 'A set of selectable cards with the semantics of its selection. One choice (the default) is a radio group: the cards are native radios sharing one name, so the set is one tab stop, the arrow keys move and select, and screen readers speak the position ("2 of 3"). Several choices are a named group of checkboxes. Each SelectableCardGroupItem is a SelectableCard whose input, name and selection come from the group.',+ props: [+ {+ name: 'label',+ type: 'string',+ description: "The group's visible label and accessible name.",+ required: true,+ },+ {+ name: 'selectionMode',+ type: "'single' | 'multiple'",+ description:+ '`single`: a radio group with one value. `multiple`: a group of checkboxes with any number of values.',+ default: "'single'",+ },+ {+ name: 'value',+ type: 'string | null | ReadonlyArray<string>',+ description:+ 'The chosen value (`single`, `null` while none is chosen) or values (`multiple`).',+ required: true,+ },+ {+ name: 'onChange',+ type: '(value: string) => void | (value: string[]) => void',+ description:+ 'Called with the chosen value (`single`) or the new list of values (`multiple`).',+ required: true,+ },+ {+ name: 'isLabelHidden',+ type: 'boolean',+ description: 'Hides the label visually; it still names the group.',+ default: 'false',+ },+ {+ name: 'description',+ type: 'string',+ description: 'Helper text under the label, linked to the group.',+ },+ {+ name: 'htmlName',+ type: 'string',+ description:+ "The name the group's value is submitted under. The radios group by a generated name. Defaults to a generated one.",+ },+ {+ name: 'isDisabled',+ type: 'boolean',+ description:+ 'Disables every card; they stay focusable and announce disabled.',+ default: 'false',+ },+ {+ name: 'orientation',+ type: "'horizontal' | 'vertical'",+ description:+ '`horizontal` wraps the cards in rows; `vertical` stacks them.',+ default: "'horizontal'",+ },+ {+ name: 'children',+ type: 'ReactNode',+ description:+ 'SelectableCardGroupItem cards. Each takes a `value` and the SelectableCard props other than isSelected and onChange.',+ required: true,+ },+ {+ name: 'containerXstyle',+ type: 'StyleXStyles',+ description:+ 'StyleX styles for the Field box around the label, description and cards (margins, positioning, sizing). The group composes Field, so it takes no root xstyle, className or style.',+ },+ {+ name: 'containerClassName',+ type: 'string',+ description:+ 'Class name for the Field box. Same targeting as containerXstyle.',+ },+ {+ name: 'containerStyle',+ type: 'CSSProperties',+ description:+ 'Inline styles for the Field box. Same targeting as containerXstyle.',+ },+ ],+ theming: {+ targets: [+ {+ className: 'astryx-selectable-card-group',+ visualProps: ['orientation', 'selectionMode'],+ },+ ],+ },+ usage: {+ description:+ 'Use it for a choice among a few rich options shown as cards: a plan, an appearance, a layout. One choice gives users the radio-group keyboard and the position they expect; use `multiple` when several cards can be on.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Give every card a `label` that names its option; it is the radio or checkbox name screen readers speak.',+ },+ {+ guidance: true,+ description:+ 'Start a single choice with a value when the product has a sensible default, so the tab stop lands on it.',+ },+ {+ guidance: false,+ description:+ 'Put buttons or links inside the cards; the whole card is the radio or checkbox target.',+ },+ {+ guidance: false,+ description:+ 'Use it for navigation or actions; use ClickableCard for those.',+ },+ ],+ },+};++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */+export const docsZh = {+ name: 'SelectableCardGroup',+ displayName: 'Selectable Card Group',+ description:+ '一组可选卡片,语义与其选择方式一致。单选(默认)是一个单选按钮组:卡片是共享同一 name 的原生单选按钮,因此整组只占一个 Tab 停靠点,方向键移动并选中,读屏软件会读出位置(“第 2 项,共 3 项”)。多选是一个带名称的复选框组。每个 SelectableCardGroupItem 都是一个 SelectableCard,其输入类型、name 和选中状态由组提供。',+ props: [+ {+ name: 'label',+ type: 'string',+ description: '组的可见标签和无障碍名称。',+ required: true,+ },+ {+ name: 'selectionMode',+ type: "'single' | 'multiple'",+ description:+ '`single`:单选按钮组,一个值。`multiple`:复选框组,任意多个值。',+ default: "'single'",+ },+ {+ name: 'value',+ type: 'string | null | ReadonlyArray<string>',+ description:+ '选中的值(`single`,未选择时为 `null`)或值列表(`multiple`)。',+ required: true,+ },+ {+ name: 'onChange',+ type: '(value: string) => void | (value: string[]) => void',+ description: '以选中的值(`single`)或新的值列表(`multiple`)调用。',+ required: true,+ },+ {+ name: 'isLabelHidden',+ type: 'boolean',+ description: '在视觉上隐藏标签;它仍为组命名。',+ default: 'false',+ },+ {+ name: 'description',+ type: 'string',+ description: '标签下方的辅助文字,并与组关联。',+ },+ {+ name: 'htmlName',+ type: 'string',+ description:+ '提交组的值时使用的名称。单选按钮按自动生成的名称分组。默认自动生成。',+ },+ {+ name: 'isDisabled',+ type: 'boolean',+ description: '禁用所有卡片;它们仍可聚焦,并读出禁用状态。',+ default: 'false',+ },+ {+ name: 'orientation',+ type: "'horizontal' | 'vertical'",+ description: '`horizontal` 将卡片按行换行排列;`vertical` 纵向堆叠。',+ default: "'horizontal'",+ },+ {+ name: 'children',+ type: 'ReactNode',+ description:+ 'SelectableCardGroupItem 卡片。每张卡片接受一个 `value`,以及除 isSelected 和 onChange 之外的 SelectableCard 属性。',+ required: true,+ },+ {+ name: 'containerXstyle',+ type: 'StyleXStyles',+ description:+ '作用于标签、描述和卡片外层 Field 容器的 StyleX 样式(外边距、定位、尺寸)。该组由 Field 组成,因此不接受根级 xstyle、className 或 style。',+ },+ {+ name: 'containerClassName',+ type: 'string',+ description: 'Field 容器的类名,作用范围与 containerXstyle 相同。',+ },+ {+ name: 'containerStyle',+ type: 'CSSProperties',+ description: 'Field 容器的内联样式,作用范围与 containerXstyle 相同。',+ },+ ],+ theming: {+ targets: [+ {+ className: 'astryx-selectable-card-group',+ visualProps: ['orientation', 'selectionMode'],+ },+ ],+ },+ usage: {+ description:+ '用于在少数以卡片呈现的丰富选项中做选择:套餐、外观、布局。单选为用户提供他们预期的单选按钮组键盘操作和位置播报;当可以同时开启多张卡片时,使用 `multiple`。',+ bestPractices: [+ {+ guidance: true,+ description:+ '为每张卡片提供一个说明其选项的 `label`;它就是读屏软件读出的单选按钮或复选框名称。',+ },+ {+ guidance: true,+ description:+ '当产品有合理的默认值时,让单选从一个值开始,这样 Tab 停靠点会落在它上面。',+ },+ {+ guidance: false,+ description:+ '在卡片内放置按钮或链接;整张卡片都是单选按钮或复选框的目标。',+ },+ {+ guidance: false,+ description: '用于导航或操作;这些场景请使用 ClickableCard。',+ },+ ],+ },+};diff --git a/packages/lab/src/SelectableCardGroup/SelectableCardGroup.test.tsx b/packages/lab/src/SelectableCardGroup/SelectableCardGroup.test.tsxnew file mode 100644index 0000000000..c093ef05dd--- /dev/null+++ b/packages/lab/src/SelectableCardGroup/SelectableCardGroup.test.tsx@@ -0,0 +1,269 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SelectableCardGroup.test.tsx+ * @input Uses SelectableCardGroup, SelectableCardGroupItem, Testing Library+ * @output Tests the group's semantics and selection+ * @position A single choice is a radio group of native radios sharing a name;+ * several choices are a named group of checkboxes.+ */++import {useState} from 'react';+import {describe, it, expect, vi} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {+ SelectableCardGroup,+ SelectableCardGroupItem,+} from './SelectableCardGroup';++const PLANS = ['Basic', 'Pro', 'Team'];++function Single({+ initial = null,+ onChange,+ isDisabled,+}: {+ initial?: string | null;+ onChange?: (value: string) => void;+ isDisabled?: boolean;+}) {+ const [value, setValue] = useState<string | null>(initial);+ return (+ <SelectableCardGroup+ label="Plan"+ description="Billed monthly"+ value={value}+ isDisabled={isDisabled}+ onChange={v => {+ setValue(v);+ onChange?.(v);+ }}>+ {PLANS.map(plan => (+ <SelectableCardGroupItem key={plan} value={plan} label={plan}>+ {plan}+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ );+}++function Multiple({onChange}: {onChange?: (value: string[]) => void}) {+ const [value, setValue] = useState<string[]>(['Basic']);+ return (+ <SelectableCardGroup+ label="Add-ons"+ selectionMode="multiple"+ value={value}+ onChange={v => {+ setValue(v);+ onChange?.(v);+ }}>+ {PLANS.map(plan => (+ <SelectableCardGroupItem key={plan} value={plan} label={plan}>+ {plan}+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ );+}++describe('SelectableCardGroup', () => {+ it('a single choice is a named radiogroup of radios sharing one name', () => {+ render(<Single initial="Pro" />);+ const group = screen.getByRole('radiogroup', {name: 'Plan'});+ expect(group).toHaveAccessibleDescription('Billed monthly');+ const radios = screen.getAllByRole('radio');+ expect(radios).toHaveLength(3);+ const names = new Set(radios.map(r => r.getAttribute('name')));+ expect(names.size).toBe(1);+ expect([...names][0]).toBeTruthy();+ expect(screen.getByRole('radio', {name: 'Pro'})).toBeChecked();+ expect(screen.queryByRole('checkbox')).toBeNull();+ });++ it('choosing a card moves the selection and reports its value', () => {+ const onChange = vi.fn();+ render(<Single initial="Basic" onChange={onChange} />);+ fireEvent.click(screen.getByText('Team'));+ expect(onChange).toHaveBeenCalledWith('Team');+ expect(screen.getByRole('radio', {name: 'Team'})).toBeChecked();+ expect(screen.getByRole('radio', {name: 'Basic'})).not.toBeChecked();+ });++ it('choosing the chosen card again changes nothing', () => {+ const onChange = vi.fn();+ render(<Single initial="Basic" onChange={onChange} />);+ fireEvent.click(screen.getByText('Basic'));+ expect(onChange).not.toHaveBeenCalled();+ expect(screen.getByRole('radio', {name: 'Basic'})).toBeChecked();+ });++ it('a disabled group selects nothing and keeps its cards focusable', () => {+ const onChange = vi.fn();+ render(<Single isDisabled onChange={onChange} />);+ expect(screen.getByRole('radiogroup')).toHaveAttribute(+ 'aria-disabled',+ 'true',+ );+ fireEvent.click(screen.getByText('Pro'));+ expect(onChange).not.toHaveBeenCalled();+ for (const radio of screen.getAllByRole('radio')) {+ expect(radio).toHaveAttribute('aria-disabled', 'true');+ expect(radio).not.toBeDisabled();+ }+ });++ it('several choices are a named group of checkboxes that toggle', () => {+ const onChange = vi.fn();+ render(<Multiple onChange={onChange} />);+ expect(screen.getByRole('group', {name: 'Add-ons'})).toBeInTheDocument();+ expect(screen.getAllByRole('checkbox')).toHaveLength(3);+ expect(screen.queryByRole('radio')).toBeNull();+ fireEvent.click(screen.getByText('Team'));+ expect(onChange).toHaveBeenLastCalledWith(['Basic', 'Team']);+ fireEvent.click(screen.getByText('Basic'));+ expect(onChange).toHaveBeenLastCalledWith(['Team']);+ expect(screen.getByRole('checkbox', {name: 'Team'})).toBeChecked();+ expect(screen.getByRole('checkbox', {name: 'Basic'})).not.toBeChecked();+ });++ it('an item outside a group throws', () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(() =>+ render(<SelectableCardGroupItem value="x" label="X" />),+ ).toThrow(/inside a SelectableCardGroup/);+ spy.mockRestore();+ });++ it('a disabled group submits nothing with its form, and keeps its grouping', () => {+ const {container} = render(+ <form>+ <Single initial="Pro" isDisabled />+ </form>,+ );+ const form = container.querySelector('form');+ if (form == null) {+ throw new Error('no form');+ }+ expect([...new FormData(form).keys()]).toEqual([]);+ const names = new Set(+ screen.getAllByRole('radio').map(r => r.getAttribute('name')),+ );+ expect(names.size).toBe(1);+ });++ it("an enabled group submits the chosen card's value under htmlName", () => {+ const {container} = render(+ <form>+ <SelectableCardGroup+ label="Plan"+ htmlName="plan"+ value="Pro"+ onChange={() => {}}>+ {PLANS.map(plan => (+ <SelectableCardGroupItem key={plan} value={plan} label={plan}>+ {plan}+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ </form>,+ );+ const form = container.querySelector('form');+ if (form == null) {+ throw new Error('no form');+ }+ expect([...new FormData(form).entries()]).toEqual([['plan', 'Pro']]);+ });++ it('a chosen card disabled on its own submits nothing, and the group keeps one form owner', () => {+ const {container} = render(+ <form>+ <SelectableCardGroup+ label="Plan"+ htmlName="plan"+ value="Team"+ onChange={() => {}}>+ {PLANS.map(plan => (+ <SelectableCardGroupItem+ key={plan}+ value={plan}+ label={plan}+ isDisabled={plan === 'Team'}>+ {plan}+ </SelectableCardGroupItem>+ ))}+ </SelectableCardGroup>+ </form>,+ );+ const form = container.querySelector('form');+ if (form == null) {+ throw new Error('no form');+ }+ expect([...new FormData(form).entries()]).toEqual([]);+ const owners = new Set(+ screen.getAllByRole('radio').map(r => r.getAttribute('form')),+ );+ expect([...owners]).toEqual(['']);+ });++ it("keeps the caller's aria-labelledby and aria-describedby beside its own", () => {+ render(+ <>+ <span id="extra-label">Billing</span>+ <span id="extra-help">Change any time</span>+ <SelectableCardGroup+ label="Plan"+ description="Billed monthly"+ aria-labelledby="extra-label"+ aria-describedby="extra-help"+ value={null}+ onChange={() => {}}>+ <SelectableCardGroupItem value="Basic" label="Basic">+ Basic+ </SelectableCardGroupItem>+ </SelectableCardGroup>+ </>,+ );+ const group = screen.getByRole('radiogroup', {name: 'Plan Billing'});+ expect(group).toHaveAccessibleDescription('Billed monthly Change any time');+ });++ it('ignores untyped root styling and warns in development', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const untyped = {className: 'root-class'} as Record<string, unknown>;+ render(+ <SelectableCardGroup+ label="Plan"+ value={null}+ onChange={() => {}}+ {...untyped}>+ <SelectableCardGroupItem value="Basic" label="Basic">+ Basic+ </SelectableCardGroupItem>+ </SelectableCardGroup>,+ );+ expect(document.querySelector('.root-class')).toBeNull();+ expect(warn).toHaveBeenCalled();+ warn.mockRestore();+ });++ it('styles the Field box through container props, not the group', () => {+ render(+ <SelectableCardGroup+ label="Plan"+ value={null}+ onChange={() => {}}+ containerClassName="field-box"+ containerStyle={{marginTop: 7}}>+ <SelectableCardGroupItem value="Basic" label="Basic">+ Basic+ </SelectableCardGroupItem>+ </SelectableCardGroup>,+ );+ const group = screen.getByRole('radiogroup', {name: 'Plan'});+ expect(group).not.toHaveClass('field-box');+ const box = group.closest('.field-box');+ expect(box).not.toBeNull();+ expect((box as HTMLElement).style.marginTop).toBe('7px');+ });+});diff --git a/packages/lab/src/SelectableCardGroup/SelectableCardGroup.tsx b/packages/lab/src/SelectableCardGroup/SelectableCardGroup.tsxnew file mode 100644index 0000000000..c718431af6--- /dev/null+++ b/packages/lab/src/SelectableCardGroup/SelectableCardGroup.tsx@@ -0,0 +1,321 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file SelectableCardGroup.tsx+ * @input Uses core SelectableCard (its input set through Core's internal+ * SelectableCardInputContext), Field (the group label and description),+ * useFieldInputStyling, useId, StyleX and the spacing tokens+ * @output Exports SelectableCardGroup, SelectableCardGroupItem and their props+ * @position Lab: a set of selectable cards with the semantics of its selection+ *+ * SYNC: When modified, update these files to stay in sync:+ * - ./SelectableCardGroup.doc.mjs (props, usage)+ * - ./index.ts (exports)+ * - /apps/storybook/stories/SelectableCardGroup.stories.tsx (stories)+ */++import {+ createContext,+ useContext,+ useId,+ useMemo,+ type ReactNode,+ type Ref,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '@astryxdesign/core';+import {Field, type FieldContainerStyleProps} from '@astryxdesign/core/Field';+import {+ SelectableCard,+ type SelectableCardProps,+} from '@astryxdesign/core/SelectableCard';+import {+ SelectableCardInputContext,+ joinAriaIDs,+ useFieldInputStyling,+ type SelectableCardInput,+} from '@astryxdesign/core/internal/selectable-card';+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';+import {mergeProps, themeProps} from '@astryxdesign/core/utils';++const styles = stylex.create({+ group: {+ display: 'flex',+ flexWrap: 'wrap',+ gap: spacingVars['--spacing-3'],+ },+ vertical: {+ flexDirection: 'column',+ flexWrap: 'nowrap',+ },+});++// =============================================================================+// Props+// =============================================================================++/** One chosen value, or none yet. */+interface SingleSelection {+ /**+ * `single` (the default): a radio group, one value. `multiple`: a group of+ * checkboxes, any number of values.+ */+ selectionMode?: 'single';+ /** The chosen card's value, or `null` while none is chosen. */+ value: string | null;+ /** Called with the value of the card the user chose. */+ onChange: (value: string) => void;+}++/** Any number of chosen values. */+interface MultipleSelection {+ selectionMode: 'multiple';+ /** The chosen cards' values. */+ value: ReadonlyArray<string>;+ /** Called with the new list of chosen values. The newest choice is last. */+ onChange: (value: string[]) => void;+}++// It composes Field: root styling goes to the Field box through `container*`+// (the input-fields family), not onto the group.+export type SelectableCardGroupProps = Omit<+ BaseProps,+ 'onChange' | 'xstyle' | 'className' | 'style'+> &+ FieldContainerStyleProps &+ (SingleSelection | MultipleSelection) & {+ /** Ref forwarded to the group element (role radiogroup or group). */+ ref?: Ref<HTMLDivElement>;+ /** The group's visible label and accessible name. */+ label: string;+ /** Hides the label visually; it still names the group. */+ isLabelHidden?: boolean;+ /** Helper text under the label, linked to the group. */+ description?: string;+ /**+ * The name the group's value is submitted under. The radios group by a+ * generated name. Defaults to a generated one.+ */+ htmlName?: string;+ /** Disables every card; they stay focusable and announce disabled. */+ isDisabled?: boolean;+ /**+ * `horizontal` (the default) wraps cards in rows; `vertical` stacks them.+ */+ orientation?: 'horizontal' | 'vertical';+ /** The SelectableCardGroupItem cards. */+ children: ReactNode;+ };++export interface SelectableCardGroupItemProps extends Omit<+ SelectableCardProps,+ 'isSelected' | 'onChange'+> {+ /** The value this card stands for in the group's `value`. */+ value: string;+}++// =============================================================================+// Context+// =============================================================================++interface GroupContextValue {+ inputType: 'checkbox' | 'radio';+ groupName: string;+ submitName: string;+ isDisabled: boolean;+ isSelected: (value: string) => boolean;+ change: (value: string, isSelected: boolean) => void;+}++const SelectableCardGroupContext = createContext<GroupContextValue | null>(+ null,+);++// =============================================================================+// Components+// =============================================================================++/**+ * A set of selectable cards with the semantics of its selection: one choice+ * is a radio group (one tab stop, arrow keys, "2 of 3" spoken), several are a+ * group of checkboxes.+ *+ * @example+ * ```+ * <SelectableCardGroup label="Plan" value={plan} onChange={setPlan}>+ * <SelectableCardGroupItem value="basic" label="Basic">Basic</SelectableCardGroupItem>+ * <SelectableCardGroupItem value="pro" label="Pro">Pro</SelectableCardGroupItem>+ * </SelectableCardGroup>+ * ```+ */+export function SelectableCardGroup(props: SelectableCardGroupProps) {+ const {+ ref,+ label,+ isLabelHidden,+ description,+ htmlName,+ isDisabled = false,+ orientation = 'horizontal',+ children,+ containerXstyle,+ containerClassName,+ containerStyle,+ selectionMode: _selectionMode,+ value: _value,+ onChange: _onChange,+ ...rest+ } = props;+ const labelID = useId();+ const inputID = useId();+ const descriptionID = useId();+ const generatedName = useId();+ const submitName = htmlName ?? generatedName;+ const {rest: groupProps, container} = useFieldInputStyling(+ 'SelectableCardGroup',+ rest,+ {containerXstyle, containerClassName, containerStyle},+ );+ const {+ 'aria-labelledby': callerLabelledBy,+ 'aria-describedby': callerDescribedBy,+ ...otherGroupProps+ } = groupProps as typeof groupProps & {+ 'aria-labelledby'?: string;+ 'aria-describedby'?: string;+ };+ const labelledBy = joinAriaIDs(labelID, callerLabelledBy);+ const describedBy = joinAriaIDs(+ description ? descriptionID : undefined,+ callerDescribedBy,+ );+ const isMultiple = props.selectionMode === 'multiple';++ const context = useMemo<GroupContextValue>(() => {+ if (props.selectionMode === 'multiple') {+ const {value, onChange} = props;+ return {+ inputType: 'checkbox',+ groupName: submitName,+ submitName,+ isDisabled,+ isSelected: v => value.includes(v),+ change: (v, isSelected) =>+ onChange(+ isSelected+ ? [...value.filter(x => x !== v), v]+ : value.filter(x => x !== v),+ ),+ };+ }+ const {value, onChange} = props;+ // The radios leave the form, so a page-unique name keeps each group+ // apart, even from another form's group with the same `htmlName`.+ return {+ inputType: 'radio',+ groupName: generatedName,+ submitName,+ isDisabled,+ isSelected: v => value === v,+ change: (v, isSelected) => {+ if (isSelected) {+ onChange(v);+ }+ },+ };+ }, [+ props.selectionMode,+ props.value,+ props.onChange,+ generatedName,+ submitName,+ isDisabled,+ ]);++ return (+ <Field+ label={label}+ isLabelHidden={isLabelHidden}+ description={description}+ inputID={inputID}+ labelID={labelID}+ isGroupLabel+ descriptionID={description ? descriptionID : undefined}+ isDisabled={isDisabled}+ {...container}>+ <div+ {...otherGroupProps}+ ref={ref}+ role={isMultiple ? 'group' : 'radiogroup'}+ aria-labelledby={labelledBy}+ aria-describedby={describedBy}+ aria-disabled={isDisabled || undefined}+ {...mergeProps(+ themeProps('selectable-card-group', {+ orientation,+ selectionMode: isMultiple ? 'multiple' : 'single',+ }),+ stylex.props(+ styles.group,+ orientation === 'vertical' && styles.vertical,+ ),+ )}>+ <SelectableCardGroupContext.Provider value={context}>+ {children}+ </SelectableCardGroupContext.Provider>+ </div>+ </Field>+ );+}++SelectableCardGroup.displayName = 'SelectableCardGroup';++/**+ * One card of a SelectableCardGroup: a SelectableCard whose input, name and+ * selection come from the group.+ */+export function SelectableCardGroupItem({+ value,+ isDisabled,+ ...props+}: SelectableCardGroupItemProps) {+ const group = useContext(SelectableCardGroupContext);+ const input = useMemo<SelectableCardInput | null>(+ () =>+ group == null+ ? null+ : {+ type: group.inputType,+ name: group.groupName,+ value,+ },+ [group, value],+ );+ if (group == null) {+ throw new Error(+ 'SelectableCardGroupItem must be rendered inside a SelectableCardGroup.',+ );+ }+ const isSelected = group.isSelected(value);+ const isCardDisabled = group.isDisabled || isDisabled === true;+ return (+ <SelectableCardInputContext value={input}>+ <SelectableCard+ {...props}+ isSelected={isSelected}+ isDisabled={isCardDisabled}+ onChange={nextSelected => group.change(value, nextSelected)}+ />+ {/* The radio cards stay out of the form, so the chosen, enabled card+ submits the group's value here. */}+ {group.inputType === 'radio' && isSelected && !isCardDisabled ? (+ <input type="hidden" name={group.submitName} value={value} />+ ) : null}+ </SelectableCardInputContext>+ );+}++SelectableCardGroupItem.displayName = 'SelectableCardGroupItem';diff --git a/packages/lab/src/SelectableCardGroup/__tests__/SelectableCardGroupRadio.a11y.chromium.spec.ts b/packages/lab/src/SelectableCardGroup/__tests__/SelectableCardGroupRadio.a11y.chromium.spec.tsnew file mode 100644index 0000000000..390b82ad40--- /dev/null+++ b/packages/lab/src/SelectableCardGroup/__tests__/SelectableCardGroupRadio.a11y.chromium.spec.ts@@ -0,0 +1,124 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SelectableCardGroupRadio.a11y.chromium.spec.ts+ * @input Uses Playwright and the a11y-spec Storybook server+ * @output Real-browser keyboard checks for a single-choice SelectableCardGroup+ * @position Its cards are native radios with one name, so they form a native+ * radio group: one tab stop on the checked card, arrow keys that move and select+ * with wrapping, Space on a focused card, and a click that never deselects.+ * jsdom has no native radio-group keyboard, so only a real engine shows it.+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++const STORY = 'lab-selectablecardgroup--single-choice';++async function open(page: Page): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`,+ {waitUntil: 'load'},+ );+ await page.getByRole('radiogroup', {name: 'Plan'}).waitFor();+}++async function checkedName(page: Page): Promise<string | null> {+ return page+ .locator('#storybook-root input[type="radio"]:checked')+ .getAttribute('aria-label');+}++async function focusedName(page: Page): Promise<string | null> {+ return page.evaluate(+ () => document.activeElement?.getAttribute('aria-label') ?? null,+ );+}++test.describe('SelectableCardGroup, single choice', () => {+ test('is a named radio group of native radios', async ({page}) => {+ await open(page);+ const group = page.getByRole('radiogroup', {name: 'Plan'});+ await expect(group.getByRole('radio')).toHaveCount(3);+ await expect(page.getByRole('checkbox')).toHaveCount(0);+ await expect(page.getByRole('radio', {name: 'Basic'})).toBeChecked();+ });++ test('one tab stop on the checked card; arrows move and select, wrapping', async ({+ page,+ }) => {+ await open(page);+ await page.getByText('Pro', {exact: true}).click();+ expect(await checkedName(page)).toBe('Pro');+ await page.evaluate(() => {+ (document.activeElement as HTMLElement | null)?.blur();+ });+ await page.keyboard.press('Tab');+ expect(await focusedName(page)).toBe('Pro');+ await page.keyboard.press('Tab');+ expect(['Basic', 'Pro', 'Team']).not.toContain(await focusedName(page));+ await page.keyboard.press('Shift+Tab');+ expect(await focusedName(page)).toBe('Pro');++ await page.keyboard.press('ArrowRight');+ expect(await focusedName(page)).toBe('Team');+ expect(await checkedName(page)).toBe('Team');+ await page.keyboard.press('ArrowRight');+ expect(await focusedName(page)).toBe('Basic');+ expect(await checkedName(page)).toBe('Basic');+ await page.keyboard.press('ArrowLeft');+ expect(await checkedName(page)).toBe('Team');+ });++ test('Space selects the focused card; a click on the chosen card keeps it', async ({+ page,+ }) => {+ await open(page);+ await page.getByRole('radio', {name: 'Team'}).focus();+ await page.keyboard.press('Space');+ expect(await checkedName(page)).toBe('Team');+ await page.getByText('Team', {exact: true}).click();+ expect(await checkedName(page)).toBe('Team');+ await page.getByText('Basic', {exact: true}).click();+ expect(await checkedName(page)).toBe('Basic');+ });+});++test('two groups that share an htmlName in separate forms stay separate', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=lab-selectablecardgroup--two-forms-shared-name&viewMode=story`,+ {waitUntil: 'load'},+ );+ await page.getByRole('radiogroup', {name: 'Second plan'}).waitFor();+ await expect(page.getByRole('radio', {name: 'First Pro'})).toBeChecked();+ await expect(page.getByRole('radio', {name: 'Second Team'})).toBeChecked();+ await page.getByRole('radio', {name: 'Second Team'}).focus();+ await page.keyboard.press('ArrowRight');+ // The arrow wraps inside the second group and leaves the first alone.+ await expect(page.getByRole('radio', {name: 'Second Basic'})).toBeChecked();+ await expect(page.getByRole('radio', {name: 'First Pro'})).toBeChecked();+ const submitted = await page.evaluate(() =>+ Array.from(document.querySelectorAll('form')).map(form =>+ Array.from(new FormData(form).entries()).map(+ ([k, v]) => `${k}=${String(v)}`,+ ),+ ),+ );+ expect(submitted).toEqual([['plan=pro'], ['plan=basic']]);+});diff --git a/packages/lab/src/SelectableCardGroup/index.ts b/packages/lab/src/SelectableCardGroup/index.tsnew file mode 100644index 0000000000..3c7603cf43--- /dev/null+++ b/packages/lab/src/SelectableCardGroup/index.ts@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SelectableCardGroup component barrel export+ */++export {+ SelectableCardGroup,+ SelectableCardGroupItem,+} from './SelectableCardGroup';+export type {+ SelectableCardGroupProps,+ SelectableCardGroupItemProps,+} from './SelectableCardGroup';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 5c7f9fcfb4..36fb89ec84 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -24,6 +24,15 @@ export {// InfoTip — accessible info-icon help affordance (RFC meta/astryx#3349)export {InfoTip, type InfoTipProps, type InfoTipSize} from './InfoTip';+// SelectableCardGroup — a set of selectable cards with the semantics of its+// selection: one choice is a radio group, several a group of checkboxes+export {+ SelectableCardGroup,+ SelectableCardGroupItem,+ type SelectableCardGroupProps,+ type SelectableCardGroupItemProps,+} from './SelectableCardGroup';+// EmojiPicker — standalone searchable emoji panelexport {EmojiPicker,diff --git a/scripts/sync-exports.js b/scripts/sync-exports.jsindex dca2c64c1f..c3c98ee101 100644--- a/scripts/sync-exports.js+++ b/scripts/sync-exports.js@@ -240,6 +240,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = ['internal/indicatorPress.stylex','internal/touch','internal/touch-sheet',+ 'internal/selectable-card',];/**