Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,44 @@
* under the License.
*/

import { render } from '../../testing';
import { render, screen } from '../../testing';
import { Alert } from '.';

test('renders Alert with default props', async () => {
const { container } = render(<Alert />);
expect(container).toHaveTextContent('Default message');
});

// WCAG 3.3.1 - Error Identification accessibility tests
test('renders with role="alert" for screen reader announcement', () => {
render(<Alert type="error">Error message</Alert>);
expect(screen.getByRole('alert')).toBeInTheDocument();
});

test('renders with aria-atomic="true" so full content is announced', () => {
render(<Alert type="error">Error message</Alert>);
expect(screen.getByRole('alert')).toHaveAttribute('aria-atomic', 'true');
});

test('uses aria-live="assertive" for error alerts', () => {
render(<Alert type="error">Error message</Alert>);
expect(screen.getByRole('alert')).toHaveAttribute(
'aria-live',
'assertive',
);
});

test('uses aria-live="polite" for warning alerts', () => {
render(<Alert type="warning">Warning message</Alert>);
expect(screen.getByRole('alert')).toHaveAttribute('aria-live', 'polite');
});

test('uses aria-live="polite" for info alerts', () => {
render(<Alert type="info">Info message</Alert>);
expect(screen.getByRole('alert')).toHaveAttribute('aria-live', 'polite');
});

test('uses aria-live="polite" for success alerts', () => {
render(<Alert type="success">Success message</Alert>);
expect(screen.getByRole('alert')).toHaveAttribute('aria-live', 'polite');
});
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export const Alert = (props: AlertProps) => {
return (
<AntdAlert
role="alert"
aria-atomic="true"
aria-live={type === 'error' ? 'assertive' : 'polite'}
type={type}
showIcon={showIcon}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
import { useId } from 'react';
import { t } from '@apache-superset/core/translation';
import { styled } from '@apache-superset/core/theme';
import { Button, Icons, InfoTooltip, Tooltip, Flex } from '..';
Expand Down Expand Up @@ -65,6 +66,12 @@ export const LabeledErrorBoundInput = ({
...props
}: LabeledErrorBoundInputProps) => {
const hasError = !!errorMessage;
// Strip colons from useId output so the id is a valid CSS selector
// (React's useId returns ":r1:" style values that break attribute lookups).
const uniqueId = useId().replace(/:/g, '');
const errorDescriptionId = hasError
? `${uniqueId}-error-description`
: undefined;
return (
<StyledFormGroup className={className}>
<Flex align="center">
Expand All @@ -78,13 +85,23 @@ export const LabeledErrorBoundInput = ({
validateStatus={
isValidating ? 'validating' : hasError ? 'error' : 'success'
}
help={errorMessage || helpText}
help={
hasError ? (
<span id={errorDescriptionId} role="alert">
{errorMessage}
</span>
) : (
helpText
)
}
hasFeedback={!!hasError}
>
{visibilityToggle || props.name === 'password' ? (
<StyledInputPassword
{...props}
{...validationMethods}
aria-invalid={hasError || undefined}
aria-describedby={errorDescriptionId}
iconRender={visible =>
visible ? (
<Tooltip title={t('Hide password.')}>
Expand All @@ -99,7 +116,12 @@ export const LabeledErrorBoundInput = ({
role="textbox"
/>
) : (
<StyledInput {...props} {...validationMethods} />
<StyledInput
{...props}
{...validationMethods}
aria-invalid={hasError || undefined}
aria-describedby={errorDescriptionId}
/>
)}
{get_url && description ? (
<Button
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,23 @@ test('should render with error theme', () => {
`,
);
});

// WCAG 3.3.1 - Error Identification accessibility tests
test('should have role="alert" for screen reader announcement', () => {
render(<BasicErrorAlert {...mockedProps} />);
const alertElement = screen.getByRole('alert');
expect(alertElement).toBeInTheDocument();
});

test('should have aria-atomic="true" so the entire alert is read as a unit', () => {
render(<BasicErrorAlert {...mockedProps} />);
const alertElement = screen.getByRole('alert');
expect(alertElement).toHaveAttribute('aria-atomic', 'true');
});

test('should contain both title and body text within the alert region', () => {
render(<BasicErrorAlert {...mockedProps} />);
const alertElement = screen.getByRole('alert');
expect(alertElement).toHaveTextContent('Error title');
expect(alertElement).toHaveTextContent('Error body');
});
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export function BasicErrorAlert({
};

return (
<div style={style} role="alert">
<div style={style} role="alert" aria-atomic="true">
<Icons.ExclamationCircleFilled iconColor={variants.text} />
<StyledContent>
<StyledTitle>{title}</StyledTitle>
Expand Down
54 changes: 51 additions & 3 deletions superset-frontend/src/components/Modal/ModalFormField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
import { ReactNode } from 'react';
import {
ReactNode,
Children,
isValidElement,
cloneElement,
useId,
} from 'react';
import { css, styled } from '@apache-superset/core/theme';
import { InfoTooltip } from '@superset-ui/core/components';

Expand Down Expand Up @@ -128,16 +134,58 @@ export function ModalFormField({
validateStatus,
hasFeedback = false,
}: ModalFormFieldProps) {
// Strip colons from useId output so the id is a valid CSS selector
// (React's useId returns ":r1:" style values that break attribute lookups).
const uniqueId = useId().replace(/:/g, '');
const errorId = error ? `${uniqueId}-error` : undefined;

// Clone the first child element to inject aria-invalid and aria-describedby
// on the real input. Many call sites wrap the input in a FormItem/Row so
// the ARIA attrs must hop through wrappers to reach the actual interactive
// element, otherwise screen readers never learn about the error.
// We always run through Children.map so the React tree shape stays stable
// across error/no-error transitions; otherwise auto-keyed children would
// unmount and remount the underlying input on every toggle, dropping focus
// mid-typing.
const applyAria = (
element: React.ReactElement<any>,
): React.ReactElement<any> => {
const ariaProps = error
? { 'aria-invalid': true, 'aria-describedby': errorId }
: {};
const wrappedChild = element.props?.children;
if (isValidElement(wrappedChild) && Children.count(wrappedChild) === 1) {
return cloneElement(element, {
children: cloneElement(
wrappedChild as React.ReactElement<any>,
ariaProps,
),
});
}
return cloneElement(element, ariaProps);
};

const enhancedChildren = Children.map(children, (child, index) => {
if (index === 0 && isValidElement(child)) {
return applyAria(child as React.ReactElement<any>);
}
return child;
});

return (
<StyledFieldContainer bottomSpacing={bottomSpacing} data-test={testId}>
<div className="control-label">
{label}
{tooltip && <InfoTooltip tooltip={tooltip} />}
{required && <span className="required">*</span>}
</div>
<div className="input-container">{children}</div>
<div className="input-container">{enhancedChildren}</div>
{helperText && <div className="helper">{helperText}</div>}
{error && <div className="error">{error}</div>}
{error && (
<div className="error" id={errorId} role="alert">
{error}
</div>
)}
</StyledFieldContainer>
);
}
33 changes: 30 additions & 3 deletions superset-frontend/src/explore/components/ControlHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
import { FC, ReactNode } from 'react';
import { FC, ReactNode, useId } from 'react';
import { t } from '@apache-superset/core/translation';
import { css, useTheme, SupersetTheme } from '@apache-superset/core/theme';
import { FormLabel, InfoTooltip, Tooltip } from '@superset-ui/core/components';
Expand All @@ -37,6 +37,10 @@ export type ControlHeaderProps = {
tooltipOnClick?: () => void;
warning?: string;
danger?: string;
// WCAG 3.3.1: error container ID shared with the input's aria-describedby.
// Passed in by wrappers like NumberControl/TextControl so there is exactly
// one live-region and one DOM id per control (no duplicate ids/alerts).
errorId?: string;
// Allow extra props from control spread patterns (e.g. {...this.props})
[key: string]: unknown;
};
Expand Down Expand Up @@ -70,8 +74,11 @@ const ControlHeader: FC<ControlHeaderProps> = ({
tooltipOnClick = () => {},
warning,
danger,
errorId: providedErrorId,
}) => {
const theme = useTheme();
const uniqueId = useId();
const errorId = providedErrorId ?? `${name || uniqueId}-error`;

if (!label) {
return null;
Expand Down Expand Up @@ -178,8 +185,28 @@ const ControlHeader: FC<ControlHeaderProps> = ({
placement="top"
title={validationErrors?.join(' ')}
>
<Icons.ExclamationCircleOutlined iconColor={theme.colorError} />
</Tooltip>{' '}
<Icons.ExclamationCircleOutlined
iconColor={theme.colorError}
aria-hidden="true"
/>
</Tooltip>
<span
id={errorId}
role="alert"
css={css`
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
`}
>
{validationErrors?.join('. ')}
</span>{' '}
Comment thread
Aitema-gmbh marked this conversation as resolved.
Resolved
</span>
)}
{renderOptionalIcons()}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
import { useRef } from 'react';
import { styled } from '@apache-superset/core/theme';
import { useId, useRef } from 'react';
import { styled, css, SupersetTheme } from '@apache-superset/core/theme';
import { InputNumber } from '@superset-ui/core/components/Input';
import ControlHeader, { ControlHeaderProps } from '../../ControlHeader';

Expand All @@ -43,6 +43,13 @@ const FullWidthInputNumber = styled(InputNumber)`
width: 100%;
`;

const fieldErrorStyles = (theme: SupersetTheme) => css`
color: ${theme.colorError};
font-size: ${theme.fontSizeSM}px;
display: block;
margin-top: ${theme.sizeUnit}px;
`;

function parseValue(value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') {
return undefined;
Expand All @@ -62,6 +69,8 @@ export default function NumberControl({
...rest
}: NumberControlProps) {
const pendingValueRef = useRef<NumberValueType>(value);
const uniqueId = useId();
const inputId = rest.name || uniqueId;

const handleChange = (val: string | number | null) => {
pendingValueRef.current = parseValue(val);
Expand All @@ -76,9 +85,17 @@ export default function NumberControl({
onChange?.(val);
};

const hasErrors =
rest.validationErrors && rest.validationErrors.length > 0;
// WCAG 3.3.1: the visually hidden live-region inside ControlHeader carries
// the id and role="alert"; this wrapper only needs to point the input at
// that same id via aria-describedby. Sharing one id per control avoids
// duplicate DOM ids and duplicate screen-reader announcements.
const errorId = hasErrors ? `${inputId}-error` : undefined;

return (
<FullWidthDiv>
<ControlHeader {...rest} />
<ControlHeader {...rest} errorId={errorId} />
<FullWidthInputNumber
min={min}
max={max}
Expand All @@ -90,7 +107,15 @@ export default function NumberControl({
onStep={handleStep}
disabled={disabled}
aria-label={rest.label}
aria-invalid={hasErrors || undefined}
aria-describedby={errorId}
id={inputId}
/>
{hasErrors && (
<span css={fieldErrorStyles}>
{rest.validationErrors!.join('. ')}
</span>
)}
</FullWidthDiv>
);
}
Loading
Loading