Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add focus method to alert #1388

Merged
merged 8 commits into from
Aug 4, 2023
Merged
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
15 changes: 13 additions & 2 deletions pages/alert/simple.page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React, { useState } from 'react';
import Alert from '~components/alert';
import React, { useEffect, useRef, useState } from 'react';
import Alert, { AlertProps } from '~components/alert';
import Button from '~components/button';
import Link from '~components/link';
import ScreenshotArea from '../utils/screenshot-area';
import SpaceBetween from '~components/space-between';
Expand All @@ -12,10 +13,19 @@ import messages from '~components/i18n/messages/all.en';

export default function AlertScenario() {
const [visible, setVisible] = useState(true);
const alertRef = useRef<AlertProps.Ref>(null);

useEffect(() => {
if (visible) {
alertRef.current?.focus();
}
}, [visible]);

return (
<I18nProvider messages={[messages]} locale="en">
<article>
<h1>Simple alert</h1>
<Button onClick={() => setVisible(!visible)}>Toggle visibility</Button>
<ScreenshotArea>
<SpaceBetween size="s">
<div className={styles['alert-container']}>
Expand All @@ -27,6 +37,7 @@ export default function AlertScenario() {
buttonText="Button text"
type="warning"
onDismiss={() => setVisible(false)}
ref={alertRef}
>
Content
<br />
Expand Down
11 changes: 9 additions & 2 deletions src/__tests__/__snapshots__/documenter.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@ when the \`dismissible\` property is set to \`true\`.",
"name": "onDismiss",
},
],
"functions": Array [],
"functions": Array [
Object {
"description": "Sets focus on the alert content.",
"name": "focus",
"parameters": Array [],
"returnType": "void",
},
],
"name": "Alert",
"properties": Array [
Object {
Expand Down Expand Up @@ -54,7 +61,7 @@ An \`onDismiss\` event is fired when a user clicks the button.",
"type": "string",
},
Object {
"defaultValue": "\\"info\\"",
"defaultValue": "'info'",
"description": "Specifies the type of message you want to display.",
"inlineType": Object {
"name": "AlertProps.Type",
Expand Down
6 changes: 6 additions & 0 deletions src/alert/__tests__/alert.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,12 @@ describe('Alert Component', () => {
wrapper.findDismissButton()!.click();
expect(onDismissSpy).toHaveBeenCalled();
});
it('can be focused through the API', () => {
let ref: AlertProps.Ref | null = null;
render(<Alert header="Important" ref={element => (ref = element)} />);
ref!.focus();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think if we remove this line the test will still past, since body element is the activeElement and Important is in it's text content.
probably render another element, focus it and then focus the alert?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, good point! Or I might just grab the CSS class for the focus container and check that..

expect(document.activeElement).toHaveClass(styles['alert-focus-wrapper']);
});
});

it('renders `action` content', () => {
Expand Down
81 changes: 42 additions & 39 deletions src/alert/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,50 @@ import { getNameFromSelector, getSubStepAllSelector } from '../internal/analytic

export { AlertProps };

export default function Alert({ type = 'info', visible = true, ...props }: AlertProps) {
const baseComponentProps = useBaseComponent('Alert');

const { funnelInteractionId, submissionAttempt, funnelState, errorCount } = useFunnel();
const { stepNumber, stepNameSelector } = useFunnelStep();
const { subStepSelector, subStepNameSelector } = useFunnelSubStep();

useEffect(() => {
if (funnelInteractionId && visible && type === 'error' && funnelState.current !== 'complete') {
const stepName = getNameFromSelector(stepNameSelector);
const subStepName = getNameFromSelector(subStepNameSelector);

errorCount.current++;

if (subStepSelector) {
FunnelMetrics.funnelSubStepError({
funnelInteractionId,
subStepSelector,
subStepName,
subStepNameSelector,
stepNumber,
stepName,
stepNameSelector,
subStepAllSelector: getSubStepAllSelector(),
});
} else {
FunnelMetrics.funnelError({
funnelInteractionId,
});
const Alert = React.forwardRef(
({ type = 'info', visible = true, ...props }: AlertProps, ref: React.Ref<AlertProps.Ref>) => {
const baseComponentProps = useBaseComponent('Alert');

const { funnelInteractionId, submissionAttempt, funnelState, errorCount } = useFunnel();
const { stepNumber, stepNameSelector } = useFunnelStep();
const { subStepSelector, subStepNameSelector } = useFunnelSubStep();

useEffect(() => {
if (funnelInteractionId && visible && type === 'error' && funnelState.current !== 'complete') {
const stepName = getNameFromSelector(stepNameSelector);
const subStepName = getNameFromSelector(subStepNameSelector);

errorCount.current++;

if (subStepSelector) {
FunnelMetrics.funnelSubStepError({
funnelInteractionId,
subStepSelector,
subStepName,
subStepNameSelector,
stepNumber,
stepName,
stepNameSelector,
subStepAllSelector: getSubStepAllSelector(),
});
} else {
FunnelMetrics.funnelError({
funnelInteractionId,
});
}

return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
errorCount.current--;
};
}

return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
errorCount.current--;
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [funnelInteractionId, visible, submissionAttempt, errorCount]);

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [funnelInteractionId, visible, submissionAttempt, errorCount]);

return <InternalAlert type={type} visible={visible} {...props} {...baseComponentProps} />;
}
return <InternalAlert type={type} visible={visible} {...props} {...baseComponentProps} ref={ref} />;
}
);

applyDisplayName(Alert, 'Alert');
export default Alert;
7 changes: 7 additions & 0 deletions src/alert/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ import { NonCancelableEventHandler } from '../internal/events';

export namespace AlertProps {
export type Type = 'success' | 'error' | 'warning' | 'info';

export interface Ref {
/**
* Sets focus on the alert content.
*/
focus(): void;
}
}

export interface AlertProps extends BaseComponentProps {
Expand Down
165 changes: 90 additions & 75 deletions src/alert/internal.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React from 'react';
import React, { useRef } from 'react';
import clsx from 'clsx';
import { InternalButton } from '../button/internal';
import { IconProps } from '../icon/interfaces';
Expand All @@ -11,6 +11,7 @@ import styles from './styles.css.js';
import { fireNonCancelableEvent } from '../internal/events';
import { useContainerBreakpoints } from '../internal/hooks/container-queries';
import { useVisualRefresh } from '../internal/hooks/use-visual-mode';
import useForwardFocus from '../internal/hooks/forward-focus';
import { AlertProps } from './interfaces';
import { InternalBaseComponentProps } from '../internal/hooks/use-base-component';
import { useMergeRefs } from '../internal/hooks/use-merge-refs';
Expand All @@ -27,84 +28,98 @@ const typeToIcon: Record<AlertProps.Type, IconProps['name']> = {

type InternalAlertProps = SomeRequired<AlertProps, 'type'> & InternalBaseComponentProps;

export default function InternalAlert({
type,
statusIconAriaLabel,
visible = true,
dismissible,
dismissAriaLabel,
children,
header,
buttonText,
action,
onDismiss,
onButtonClick,
__internalRootRef = null,
...rest
}: InternalAlertProps) {
const baseProps = getBaseProps(rest);
const i18n = useInternalI18n('alert');
const InternalAlert = React.forwardRef(
(
{
type,
statusIconAriaLabel,
visible = true,
dismissible,
dismissAriaLabel,
children,
header,
buttonText,
action,
onDismiss,
onButtonClick,
__internalRootRef = null,
...rest
}: InternalAlertProps,
ref: React.Ref<AlertProps.Ref>
) => {
const baseProps = getBaseProps(rest);
const i18n = useInternalI18n('alert');

const [breakpoint, breakpointRef] = useContainerBreakpoints(['xs']);
const mergedRef = useMergeRefs(breakpointRef, __internalRootRef);
const focusRef = useRef<HTMLDivElement>(null);
useForwardFocus(ref, focusRef);

const isRefresh = useVisualRefresh();
const size = isRefresh ? 'normal' : header && children ? 'big' : 'normal';
const [breakpoint, breakpointRef] = useContainerBreakpoints(['xs']);
const mergedRef = useMergeRefs(breakpointRef, __internalRootRef);

const actionButton = action || (
<InternalButton
className={styles['action-button']}
onClick={() => fireNonCancelableEvent(onButtonClick)}
formAction="none"
>
{buttonText}
</InternalButton>
);
const isRefresh = useVisualRefresh();
const size = isRefresh ? 'normal' : header && children ? 'big' : 'normal';

const hasAction = Boolean(action || buttonText);
const analyticsAttributes = {
[DATA_ATTR_ANALYTICS_ALERT]: type,
};
const actionButton = action || (
<InternalButton
className={styles['action-button']}
onClick={() => fireNonCancelableEvent(onButtonClick)}
formAction="none"
>
{buttonText}
</InternalButton>
);

return (
<div
{...baseProps}
{...analyticsAttributes}
aria-hidden={!visible}
className={clsx(
styles.root,
{ [styles.hidden]: !visible },
baseProps.className,
styles[`breakpoint-${breakpoint}`]
)}
ref={mergedRef}
>
<VisualContext contextName="alert">
<div className={clsx(styles.alert, styles[`type-${type}`])}>
<div className={clsx(styles.icon, styles.text)} role="img" aria-label={statusIconAriaLabel}>
<InternalIcon name={typeToIcon[type]} size={size} />
</div>
<div className={styles.body}>
<div className={clsx(styles.message, styles.text)}>
{header && <div className={styles.header}>{header}</div>}
<div className={styles.content}>{children}</div>
const hasAction = Boolean(action || buttonText);
const analyticsAttributes = {
[DATA_ATTR_ANALYTICS_ALERT]: type,
};

return (
<div
{...baseProps}
{...analyticsAttributes}
aria-hidden={!visible}
className={clsx(
styles.root,
{ [styles.hidden]: !visible },
baseProps.className,
styles[`breakpoint-${breakpoint}`]
)}
ref={mergedRef}
>
<VisualContext contextName="alert">
<div className={clsx(styles.alert, styles[`type-${type}`], styles[`icon-size-${size}`])}>
<div className={styles['alert-mobile-block']}>
<div className={styles['alert-focus-wrapper']} tabIndex={-1} ref={focusRef}>
<div className={clsx(styles.icon, styles.text)} role="img" aria-label={statusIconAriaLabel}>
<InternalIcon name={typeToIcon[type]} size={size} />
</div>
<div className={styles.body}>
<div className={clsx(styles.message, styles.text)}>
{header && <div className={styles.header}>{header}</div>}
<div className={styles.content}>{children}</div>
</div>
</div>
</div>
{hasAction && <div className={styles.action}>{actionButton}</div>}
</div>
{hasAction && <div className={styles.action}>{actionButton}</div>}
{dismissible && (
<div className={styles.dismiss}>
<InternalButton
className={styles['dismiss-button']}
variant="icon"
iconName="close"
formAction="none"
ariaLabel={i18n('dismissAriaLabel', dismissAriaLabel)}
onClick={() => fireNonCancelableEvent(onDismiss)}
/>
</div>
)}
</div>
{dismissible && (
<div className={styles.dismiss}>
<InternalButton
className={styles['dismiss-button']}
variant="icon"
iconName="close"
formAction="none"
ariaLabel={i18n('dismissAriaLabel', dismissAriaLabel)}
onClick={() => fireNonCancelableEvent(onDismiss)}
/>
</div>
)}
</div>
</VisualContext>
</div>
);
}
</VisualContext>
</div>
);
}
);

export default InternalAlert;
Loading
Loading