Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/components/Badge/Badge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export type BadgeProps = BadgeText | BadgeDot

/**
* Компонент Badge
* Точка с accessibilityLabel или aria-label доступна скринридеру, без имени декоративна.
* @param children - Текст внутри бейджа
* @param dot - Отображать бейдж в форме точки
* @param severity - Выбор варианта стиля компонента
Expand All @@ -75,8 +76,10 @@ export const Badge = memo<BadgeProps>(
style,
testID,
accessibilityLabel,
'aria-label': ariaLabel,
...rest
}) => {
const resolvedAccessibilityLabel = ariaLabel ?? accessibilityLabel
badgeStyles.useVariants({ severity: adaptBadgeSeverity(severity), size })
// На iOS пересоздание Text сбрасывает старое измерение при уменьшении системного шрифта.
const { fontScale } = useWindowDimensions()
Expand All @@ -93,9 +96,9 @@ export const Badge = memo<BadgeProps>(

return (
<View
accessibilityLabel={accessibilityLabel ?? children}
accessibilityLabel={resolvedAccessibilityLabel ?? children}
accessibilityRole='text'
accessible={!dot || accessibilityLabel !== undefined}
accessible={!dot || resolvedAccessibilityLabel !== undefined}
style={[badgeStyles.container, style]}
{...rest}
>
Expand Down
12 changes: 8 additions & 4 deletions src/components/Badge/__tests__/Badge.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,14 @@ describe('Badge', () => {
expect(queryByRole('text')).toBeNull()
})

test('делает точку с accessibilityLabel одним доступным элементом', () => {
const { getByRole, getAllByRole } = render(
<Badge dot accessibilityLabel='Есть новые уведомления' />
)
test.each([
{
name: 'accessibilityLabel',
props: { accessibilityLabel: 'Есть новые уведомления' },
},
{ name: 'aria-label', props: { 'aria-label': 'Есть новые уведомления' } },
])('делает точку с $name одним доступным элементом', ({ props }) => {
const { getByRole, getAllByRole } = render(<Badge {...props} dot />)

expect(
getByRole('text', { name: 'Есть новые уведомления' })
Expand Down
4 changes: 3 additions & 1 deletion src/components/Button/Button.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<BadgeProps>`. Размещается
в верхнем правом углу, не меняет размер кнопки и остаётся видимым при
`loading` и `disabled`
Expand Down
35 changes: 23 additions & 12 deletions src/components/Button/__tests__/ButtonWithBadge.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { BaseButtonProps } from '../types'

type TestButtonProps = Pick<
BaseButtonProps<never>,
'badge' | 'loading' | 'disabled' | 'accessibilityLabel'
'badge' | 'loading' | 'disabled' | 'accessibilityLabel' | 'aria-busy'
>

describe.each([
Expand Down Expand Up @@ -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: <Badge dot testID='CartBadge' />, ...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: <Badge dot testID='CartBadge' />,
'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 })
)
}
)
})
1 change: 1 addition & 0 deletions src/components/Button/internal/BaseButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export const BaseButton = memo<BaseButtonComponentProps>(
disabled: interactionDisabled,
busy: loading,
}}
aria-busy={loading}
disabled={interactionDisabled}
ref={pressableRef}
style={(state) => [
Expand Down
2 changes: 1 addition & 1 deletion src/components/Button/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export interface BaseButtonProps<
*/
rounded?: boolean
/**
* Состояние загрузки кнопки
* Состояние загрузки кнопки. Определяет busy независимо от внешних accessibility-пропсов.
* @default false
*/
loading?: boolean
Expand Down
3 changes: 3 additions & 0 deletions src/components/Input/InputText/InputText.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ export function InputFields({ showInfo }: { showInfo: () => void }) {

InputCaption озвучивается отдельно, `accessibilityHint` задаётся явно.

Имя кнопки очистки задаётся через `clearButtonAccessibilityLabel`. Если prop не
передан или равен пустой строке, используется «Очистить поле».

Увеличенный системный шрифт может увеличивать высоту поля.

## Связанные компоненты
Expand Down
6 changes: 5 additions & 1 deletion src/components/Input/core/InputControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type InputControlProps = Pick<
| 'required'
| 'disabled'
| 'clearable'
| 'clearButtonAccessibilityLabel'
| 'inputStyle'
| 'renderTextInput'
> & {
Expand Down Expand Up @@ -74,6 +75,7 @@ export const InputControl = ({
required,
disabled,
clearable,
clearButtonAccessibilityLabel,
inputStyle,
renderTextInput,
controller,
Expand Down Expand Up @@ -158,7 +160,9 @@ export const InputControl = ({
<InputTrailingContent variant={variant}>
{isClearVisible ? (
<InputIconButton
accessibilityLabel={inputStrings.clearButton}
accessibilityLabel={
clearButtonAccessibilityLabel || inputStrings.clearButton
}
getIconColor={({ components }) => components.inputtext.root.color}
icon={IconX}
testID={makeTestId('ClearButton')}
Expand Down
2 changes: 2 additions & 0 deletions src/components/Input/core/InputField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export const InputField = ({
state = 'default',
disabled = false,
clearable = true,
clearButtonAccessibilityLabel,
ref,
style,
inputStyle,
Expand Down Expand Up @@ -141,6 +142,7 @@ export const InputField = ({
{addonContent(leftAddon)}
</InputGroupContext.Provider>
<InputControl
clearButtonAccessibilityLabel={clearButtonAccessibilityLabel}
clearable={clearable}
controller={controller}
disabled={disabled}
Expand Down
37 changes: 37 additions & 0 deletions src/components/Input/core/__tests__/InputAccessibility.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,43 @@ const components = [
]

describe('Input: доступное имя и состояние', () => {
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(
<Component
clearable
clearButtonAccessibilityLabel={clearButtonAccessibilityLabel}
label='Email'
value='name@example.com'
/>
)

expect(getByRole('button', { name: expectedLabel })).toBeOnTheScreen()
expect(getByLabelText('Email')).toHaveDisplayValue('name@example.com')
}
)

test.each(
components.flatMap(({ name, Component }) =>
[false, true].map((required) => ({
Expand Down
5 changes: 5 additions & 0 deletions src/components/Input/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@ export interface InputNativeProps extends Omit<
* @default true
*/
clearable?: boolean
/**
* Имя кнопки очистки для скринридера. Пустая строка использует имя по умолчанию.
* @default 'Очистить поле'
*/
clearButtonAccessibilityLabel?: string
/** Внешний контейнер: размеры и отступы */
style?: StyleProp<ViewStyle>
/** Стиль нативного ввода */
Expand Down
8 changes: 5 additions & 3 deletions src/components/Tag/Tag.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ export function DeliveryStatus() {
Текст масштабируется с системным шрифтом и остаётся однострочным; при нехватке
ширины сокращается многоточием.

Скринридер озвучивает видимый текст или заданный `accessibilityLabel` без
дублирования. Иконка декоративная.
Скринридер озвучивает видимый текст или заданное доступное имя без дублирования.
Имя задаётся через `accessibilityLabel` или `aria-label`, приоритет у
`aria-label`. Явный `accessible={false}` отключает фокус корневого элемента.
Иконка декоративная.

Для обработки нажатия используйте интерактивного родителя. Доступное имя и роль
задавайте родителю, оставляя Tag без собственного `accessibilityLabel`.
задавайте родителю, оставляя Tag без собственного доступного имени.

## Макет

Expand Down
12 changes: 8 additions & 4 deletions src/components/Tag/Tag.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ const tagIcons: Record<TagSeverity, SvgSource> = {

/**
* Используется для маркировки элементов интерфейса
* Доступное имя задаётся через 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<TagProps>(
Expand All @@ -88,15 +89,18 @@ export const Tag = memo<TagProps>(
Icon,
testID,
collapsable,
accessible,
accessibilityLabel,
'aria-label': ariaLabel,
...rest
}) => {
// На iOS пересоздание Text сбрасывает измерения при смене масштаба шрифта.
const { fontScale } = useWindowDimensions()
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 })

Expand All @@ -106,9 +110,9 @@ export const Tag = memo<TagProps>(
style={style}
testID={testID || TagTestId.root}
{...rest}
accessibilityLabel={accessibilityLabel}
accessibilityLabel={resolvedAccessibilityLabel}
accessibilityRole={hasAccessibilityLabel ? 'text' : undefined}
accessible={hasAccessibilityLabel}
accessible={accessible ?? hasAccessibilityLabel}
>
<View
accessibilityElementsHidden={hasAccessibilityLabel}
Expand Down
57 changes: 34 additions & 23 deletions src/components/Tag/__tests__/Tag.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,32 +111,43 @@ describe('Tag', () => {
expect(screen.getByTestId(TagTestId.root)).toHaveProp('accessible', false)
})

test('использует accessibilityLabel как единое имя и скрывает дочерний текст', () => {
const { rerender } = render(
<Tag
Icon={IconCheck}
accessibilityLabel='Статус заказа: доставлен'
text='Доставлен'
/>
)
test.each([
{
name: 'accessibilityLabel',
props: { accessibilityLabel: 'Статус заказа: доставлен' },
},
{ name: 'aria-label', props: { 'aria-label': 'Статус заказа: доставлен' } },
])(
'использует $name как единое имя и скрывает дочерний текст',
({ props }) => {
const { rerender } = render(
<Tag Icon={IconCheck} {...props} text='Доставлен' />
)

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(<Tag {...props} accessible={false} text='Доставлен' />)

rerender(<Tag Icon={IconCheck} text='Доставлен' />)
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(<Tag Icon={IconCheck} text='Доставлен' />)

expect(screen.getAllByRole('text')).toHaveLength(1)
expect(screen.getByRole('text', { name: 'Доставлен' })).toBeOnTheScreen()
expect(
screen.queryByRole('text', { name: 'Статус заказа: доставлен' })
).toBeNull()
}
)

test('скрывает декоративную иконку от accessibility', () => {
render(<Tag text='Доставлен' />)
Expand Down
Loading