diff --git a/src/components/Badge/Badge.tsx b/src/components/Badge/Badge.tsx index 51469817..127e959d 100644 --- a/src/components/Badge/Badge.tsx +++ b/src/components/Badge/Badge.tsx @@ -59,6 +59,7 @@ export type BadgeProps = BadgeText | BadgeDot /** * Компонент Badge + * Точка с accessibilityLabel или aria-label доступна скринридеру, без имени декоративна. * @param children - Текст внутри бейджа * @param dot - Отображать бейдж в форме точки * @param severity - Выбор варианта стиля компонента @@ -75,8 +76,10 @@ export const Badge = memo( style, testID, accessibilityLabel, + 'aria-label': ariaLabel, ...rest }) => { + const resolvedAccessibilityLabel = ariaLabel ?? accessibilityLabel badgeStyles.useVariants({ severity: adaptBadgeSeverity(severity), size }) // На iOS пересоздание Text сбрасывает старое измерение при уменьшении системного шрифта. const { fontScale } = useWindowDimensions() @@ -93,9 +96,9 @@ export const Badge = memo( return ( diff --git a/src/components/Badge/__tests__/Badge.test.tsx b/src/components/Badge/__tests__/Badge.test.tsx index c178ec85..b69b4e51 100644 --- a/src/components/Badge/__tests__/Badge.test.tsx +++ b/src/components/Badge/__tests__/Badge.test.tsx @@ -44,10 +44,14 @@ describe('Badge', () => { expect(queryByRole('text')).toBeNull() }) - test('делает точку с accessibilityLabel одним доступным элементом', () => { - const { getByRole, getAllByRole } = render( - - ) + test.each([ + { + name: 'accessibilityLabel', + props: { accessibilityLabel: 'Есть новые уведомления' }, + }, + { name: 'aria-label', props: { 'aria-label': 'Есть новые уведомления' } }, + ])('делает точку с $name одним доступным элементом', ({ props }) => { + const { getByRole, getAllByRole } = render() expect( getByRole('text', { name: 'Есть новые уведомления' }) diff --git a/src/components/Button/Button.md b/src/components/Button/Button.md index bbf53b41..cf3cc73d 100644 --- a/src/components/Button/Button.md +++ b/src/components/Button/Button.md @@ -30,7 +30,9 @@ export function OpenCartButton({ onPress }: { onPress: () => void }) { По умолчанию `primary` - `size` — `small | base | large | xlarge`. По умолчанию `base` - `rounded` — полное скругление углов. По умолчанию `false` -- `loading` — показывает индикатор вместо иконки. По умолчанию `false` +- `loading` — показывает индикатор вместо иконки. По умолчанию `false`. + Определяет `busy`, независимо от переданных `accessibilityState.busy` и + `aria-busy` - `badge` — готовый элемент `Badge` типа `ReactElement`. Размещается в верхнем правом углу, не меняет размер кнопки и остаётся видимым при `loading` и `disabled` diff --git a/src/components/Button/__tests__/ButtonWithBadge.test.tsx b/src/components/Button/__tests__/ButtonWithBadge.test.tsx index e183a3d4..d7e4777a 100644 --- a/src/components/Button/__tests__/ButtonWithBadge.test.tsx +++ b/src/components/Button/__tests__/ButtonWithBadge.test.tsx @@ -8,7 +8,7 @@ import type { BaseButtonProps } from '../types' type TestButtonProps = Pick< BaseButtonProps, - 'badge' | 'loading' | 'disabled' | 'accessibilityLabel' + 'badge' | 'loading' | 'disabled' | 'accessibilityLabel' | 'aria-busy' > describe.each([ @@ -55,16 +55,27 @@ describe.each([ }) test.each([ - { name: 'loading', loading: true }, - { name: 'disabled', disabled: true }, - ])('сохраняет точку при $name', ({ name: _name, ...state }) => { - const { getByRole, getByTestId } = render( - createButton({ badge: , ...state }) - ) + { name: 'loading', loading: true, ariaBusy: false, busy: true }, + { name: 'disabled', disabled: true, ariaBusy: true, busy: false }, + ])( + 'сохраняет точку и состояние доступности при $name', + ({ name: _name, ariaBusy, busy, ...state }) => { + const { getByRole, getByTestId } = render( + createButton({ + badge: , + 'aria-busy': ariaBusy, + ...state, + }) + ) - expect( - getByTestId('CartBadge', { includeHiddenElements: true }) - ).toBeOnTheScreen() - expect(getByRole('button')).toBeDisabled() - }) + expect( + getByTestId('CartBadge', { includeHiddenElements: true }) + ).toBeOnTheScreen() + expect(getByRole('button')).toBeDisabled() + expect(getByRole('button')).toHaveProp( + 'accessibilityState', + expect.objectContaining({ busy }) + ) + } + ) }) diff --git a/src/components/Button/internal/BaseButton.tsx b/src/components/Button/internal/BaseButton.tsx index b2c79284..0bbe27cc 100644 --- a/src/components/Button/internal/BaseButton.tsx +++ b/src/components/Button/internal/BaseButton.tsx @@ -64,6 +64,7 @@ export const BaseButton = memo( disabled: interactionDisabled, busy: loading, }} + aria-busy={loading} disabled={interactionDisabled} ref={pressableRef} style={(state) => [ diff --git a/src/components/Button/types.ts b/src/components/Button/types.ts index 07d1024d..f88837d9 100644 --- a/src/components/Button/types.ts +++ b/src/components/Button/types.ts @@ -44,7 +44,7 @@ export interface BaseButtonProps< */ rounded?: boolean /** - * Состояние загрузки кнопки + * Состояние загрузки кнопки. Определяет busy независимо от внешних accessibility-пропсов. * @default false */ loading?: boolean diff --git a/src/components/Input/InputText/InputText.md b/src/components/Input/InputText/InputText.md index f8210984..16d0637f 100644 --- a/src/components/Input/InputText/InputText.md +++ b/src/components/Input/InputText/InputText.md @@ -79,6 +79,9 @@ export function InputFields({ showInfo }: { showInfo: () => void }) { InputCaption озвучивается отдельно, `accessibilityHint` задаётся явно. +Имя кнопки очистки задаётся через `clearButtonAccessibilityLabel`. Если prop не +передан или равен пустой строке, используется «Очистить поле». + Увеличенный системный шрифт может увеличивать высоту поля. ## Связанные компоненты diff --git a/src/components/Input/core/InputControl.tsx b/src/components/Input/core/InputControl.tsx index 3e7f5f55..bf948251 100644 --- a/src/components/Input/core/InputControl.tsx +++ b/src/components/Input/core/InputControl.tsx @@ -26,6 +26,7 @@ type InputControlProps = Pick< | 'required' | 'disabled' | 'clearable' + | 'clearButtonAccessibilityLabel' | 'inputStyle' | 'renderTextInput' > & { @@ -74,6 +75,7 @@ export const InputControl = ({ required, disabled, clearable, + clearButtonAccessibilityLabel, inputStyle, renderTextInput, controller, @@ -158,7 +160,9 @@ export const InputControl = ({ {isClearVisible ? ( components.inputtext.root.color} icon={IconX} testID={makeTestId('ClearButton')} diff --git a/src/components/Input/core/InputField.tsx b/src/components/Input/core/InputField.tsx index 84cb6376..202c792a 100644 --- a/src/components/Input/core/InputField.tsx +++ b/src/components/Input/core/InputField.tsx @@ -77,6 +77,7 @@ export const InputField = ({ state = 'default', disabled = false, clearable = true, + clearButtonAccessibilityLabel, ref, style, inputStyle, @@ -141,6 +142,7 @@ export const InputField = ({ {addonContent(leftAddon)} { + test.each( + components.flatMap(({ name, Component }) => + [ + { + name: `${name}: пользовательское имя очистки`, + clearButtonAccessibilityLabel: 'Clear input', + expectedLabel: 'Clear input', + }, + { + name: `${name}: без переопределения`, + clearButtonAccessibilityLabel: undefined, + expectedLabel: 'Очистить поле', + }, + { + name: `${name}: пустое переопределение`, + clearButtonAccessibilityLabel: '', + expectedLabel: 'Очистить поле', + }, + ].map((props) => ({ ...props, Component })) + ) + )( + 'задаёт имя кнопки отдельно от имени поля в $name', + ({ Component, clearButtonAccessibilityLabel, expectedLabel }) => { + const { getByRole, getByLabelText } = render( + + ) + + expect(getByRole('button', { name: expectedLabel })).toBeOnTheScreen() + expect(getByLabelText('Email')).toHaveDisplayValue('name@example.com') + } + ) + test.each( components.flatMap(({ name, Component }) => [false, true].map((required) => ({ diff --git a/src/components/Input/core/types.ts b/src/components/Input/core/types.ts index d448d916..1d1805de 100644 --- a/src/components/Input/core/types.ts +++ b/src/components/Input/core/types.ts @@ -102,6 +102,11 @@ export interface InputNativeProps extends Omit< * @default true */ clearable?: boolean + /** + * Имя кнопки очистки для скринридера. Пустая строка использует имя по умолчанию. + * @default 'Очистить поле' + */ + clearButtonAccessibilityLabel?: string /** Внешний контейнер: размеры и отступы */ style?: StyleProp /** Стиль нативного ввода */ diff --git a/src/components/Tag/Tag.md b/src/components/Tag/Tag.md index 62feef69..3bfaebc6 100644 --- a/src/components/Tag/Tag.md +++ b/src/components/Tag/Tag.md @@ -29,11 +29,13 @@ export function DeliveryStatus() { Текст масштабируется с системным шрифтом и остаётся однострочным; при нехватке ширины сокращается многоточием. -Скринридер озвучивает видимый текст или заданный `accessibilityLabel` без -дублирования. Иконка декоративная. +Скринридер озвучивает видимый текст или заданное доступное имя без дублирования. +Имя задаётся через `accessibilityLabel` или `aria-label`, приоритет у +`aria-label`. Явный `accessible={false}` отключает фокус корневого элемента. +Иконка декоративная. Для обработки нажатия используйте интерактивного родителя. Доступное имя и роль -задавайте родителю, оставляя Tag без собственного `accessibilityLabel`. +задавайте родителю, оставляя Tag без собственного доступного имени. ## Макет diff --git a/src/components/Tag/Tag.tsx b/src/components/Tag/Tag.tsx index 6b513526..c8bc8b75 100644 --- a/src/components/Tag/Tag.tsx +++ b/src/components/Tag/Tag.tsx @@ -74,8 +74,9 @@ const tagIcons: Record = { /** * Используется для маркировки элементов интерфейса + * Доступное имя задаётся через accessibilityLabel или aria-label. * Внутри интерактивного родителя задавайте доступное имя родителю, - * оставляя Tag без собственного accessibilityLabel + * оставляя Tag без собственного имени * @see https://www.figma.com/design/Q1BWgZ7zoV5UzlBOnjW0cM/UI-Kit--DS--v2.1?node-id=21-1238 */ export const Tag = memo( @@ -88,7 +89,9 @@ export const Tag = memo( Icon, testID, collapsable, + accessible, accessibilityLabel, + 'aria-label': ariaLabel, ...rest }) => { // На iOS пересоздание Text сбрасывает измерения при смене масштаба шрифта. @@ -96,7 +99,8 @@ export const Tag = memo( const resolvedSeverity = severity === 'basic' ? 'primary' : severity const colorSchemeKey = resolvedSeverity === 'warning' ? 'warn' : resolvedSeverity - const hasAccessibilityLabel = accessibilityLabel !== undefined + const resolvedAccessibilityLabel = ariaLabel ?? accessibilityLabel + const hasAccessibilityLabel = resolvedAccessibilityLabel !== undefined tagStyles.useVariants({ severity: resolvedSeverity }) @@ -106,9 +110,9 @@ export const Tag = memo( style={style} testID={testID || TagTestId.root} {...rest} - accessibilityLabel={accessibilityLabel} + accessibilityLabel={resolvedAccessibilityLabel} accessibilityRole={hasAccessibilityLabel ? 'text' : undefined} - accessible={hasAccessibilityLabel} + accessible={accessible ?? hasAccessibilityLabel} > { expect(screen.getByTestId(TagTestId.root)).toHaveProp('accessible', false) }) - test('использует accessibilityLabel как единое имя и скрывает дочерний текст', () => { - const { rerender } = render( - - ) + test.each([ + { + name: 'accessibilityLabel', + props: { accessibilityLabel: 'Статус заказа: доставлен' }, + }, + { name: 'aria-label', props: { 'aria-label': 'Статус заказа: доставлен' } }, + ])( + 'использует $name как единое имя и скрывает дочерний текст', + ({ props }) => { + const { rerender } = render( + + ) + + expect(screen.getAllByRole('text')).toHaveLength(1) + expect( + screen.getByRole('text', { name: 'Статус заказа: доставлен' }) + ).toBe(screen.getByTestId(TagTestId.root)) + expect(screen.queryByRole('text', { name: 'Доставлен' })).toBeNull() + expect( + screen.getByText('Доставлен', { includeHiddenElements: true }) + ).toBeOnTheScreen() - expect(screen.getAllByRole('text')).toHaveLength(1) - expect(screen.getByRole('text', { name: 'Статус заказа: доставлен' })).toBe( - screen.getByTestId(TagTestId.root) - ) - expect(screen.queryByRole('text', { name: 'Доставлен' })).toBeNull() - expect( - screen.getByText('Доставлен', { includeHiddenElements: true }) - ).toBeOnTheScreen() + rerender() - rerender() + expect( + screen.queryByRole('text', { name: 'Статус заказа: доставлен' }) + ).toBeNull() - expect(screen.getAllByRole('text')).toHaveLength(1) - expect(screen.getByRole('text', { name: 'Доставлен' })).toBeOnTheScreen() - expect( - screen.queryByRole('text', { name: 'Статус заказа: доставлен' }) - ).toBeNull() - }) + rerender() + + expect(screen.getAllByRole('text')).toHaveLength(1) + expect(screen.getByRole('text', { name: 'Доставлен' })).toBeOnTheScreen() + expect( + screen.queryByRole('text', { name: 'Статус заказа: доставлен' }) + ).toBeNull() + } + ) test('скрывает декоративную иконку от accessibility', () => { render()