import { useState } from 'react'; import { Meta, StoryObj } from '@storybook/react-webpack5'; import { expect, fn, userEvent, waitFor, within } from 'storybook/test'; import { Bank } from '@transferwise/icons'; import Button from '../../../Button'; import { useRtlDiffI18n, withRTLDiff } from '../../../../.storybook/decorators/RtlDiffDecorator'; import { withVariantConfig } from '../../../../.storybook/helpers'; import { CriticalBanner } from '../CriticalBanner'; const meta: Meta = { component: CriticalBanner, title: 'Prompts/CriticalBanner/Tests', tags: ['!autodocs', '!manifest'], }; export default meta; type Story = StoryObj; const wait = async (ms: number) => new Promise((resolve) => { setTimeout(resolve, ms); }); const ANIMATION_DURATION = 200; // 150ms animation + 50ms buffer const ENTRY_ANIMATION_DURATION = 950; // 500ms delay + 400ms animation + 50ms buffer const longDescription = 'We have detected unusual activity on your account that does not match your typical usage patterns. To protect your funds and personal information, we have temporarily restricted access. Please verify your identity to restore full access to your account.'; const BACKGROUND_SCROLL_CONTENT = [ 'Manage your card settings, limits, and delivery details from this page.', 'Your recent payments, subscriptions, and cash withdrawals will appear here.', 'Freeze your card any time if it is lost, stolen, or somewhere unexpected.', 'Set spending limits for online, in-store, and contactless payments.', 'Add your card to a digital wallet for quicker checkout in supported stores.', 'Choose the currency balance you want to spend from before you travel.', 'Review fees before using an ATM or paying in a currency you do not hold.', 'Order a replacement card if yours is damaged or about to expire.', 'Keep your delivery address up to date so new cards arrive in the right place.', 'Contact support if a card payment looks unfamiliar or incorrect.', ]; function AllVariants({ gap = '1rem' }: { gap?: string }) { const [states, setStates] = useState({ negativeExpanded: true, negativeCollapsed: false, warningExpanded: true, warningCollapsed: false, neutralExpanded: true, successExpanded: true, noTitle: false, withMedia: true, withBothActions: true, }); const toggle = (key: keyof typeof states) => setStates((prev) => ({ ...prev, [key]: !prev[key] })); return (
toggle('negativeExpanded')} /> toggle('negativeCollapsed')} /> toggle('warningExpanded')} /> toggle('warningCollapsed')} /> toggle('neutralExpanded')} /> toggle('successExpanded')} /> toggle('noTitle')} /> } }} action={{ label: 'Connect bank', onClick: fn() }} expanded={states.withMedia} onToggle={() => toggle('withMedia')} /> toggle('withBothActions')} />
); } /** * All four sentiments in both expanded and collapsed states, with and without * title, media variants, and action combinations. Used for Chromatic visual * regression across default, dark, bright-green, and forest-green themes. */ export const Variants: Story = { render: () => , ...withVariantConfig(['default', 'dark', 'bright-green', 'forest-green']), }; /** Mobile viewport regression test with all variants. */ export const MobileVariants: Story = { render: () => , ...withVariantConfig(['mobile']), }; /** Neutral background regression test with page content scrolled under the sticky banner. */ export const BackgroundIsNotTransparent: Story = { args: { sentiment: 'neutral', }, argTypes: { sentiment: { control: 'radio', options: ['negative', 'warning', 'neutral', 'success'], }, }, render: function Render({ sentiment }) { return (

Debit card

Spend in 150+ currencies

{BACKGROUND_SCROLL_CONTENT.map((paragraph) => (

{paragraph}

))}
); }, play: async ({ canvasElement }) => { const scrollContainer = canvasElement.querySelector( '[data-testid="background-scroll-container"]', ); if (scrollContainer) { scrollContainer.scrollTop = 250; await wait(ENTRY_ANIMATION_DURATION); } }, ...withVariantConfig(['mobile'], { parameters: { controls: { include: ['sentiment'] }, }, }), }; /** Mobile entry animation visual regression test. */ export const AnimatedEntryMobile: Story = { render: function Render() { return ( ); }, ...withVariantConfig(['mobile'], { parameters: { chromatic: { pauseAnimationAtEnd: true }, }, }), }; /** * Tests keyboard navigation and interaction: * - Tab focuses the first chevron toggle button * - Enter toggles expanded/collapsed state * - Tab moves focus to the action button (when expanded) * - Tab moves to the next banner's toggle */ export const KeyboardInteraction: Story = { render: function Render() { const [expanded1, setExpanded1] = useState(true); const [expanded2, setExpanded2] = useState(false); return (
setExpanded1(!expanded1)} /> setExpanded2(!expanded2)} />
); }, play: async ({ canvasElement }) => { const canvas = within(canvasElement); // Wait for the collapse button to appear (viewport change needs time to apply) const collapseBtn = await canvas.findByRole('button', { name: /^collapse$/i }); // Tab to first toggle (Collapse button since first banner is expanded) await userEvent.tab(); await expect(collapseBtn).toHaveFocus(); // Space collapses the first banner await userEvent.keyboard(' '); await wait(ANIMATION_DURATION); // After collapsing, the button label changes to "Expand" await waitFor(async () => { const expandBtns = canvas.getAllByRole('button', { name: /^expand$/i }); await expect(expandBtns).toHaveLength(2); await expect(expandBtns[0]).toHaveFocus(); }); await userEvent.tab(); await waitFor(async () => { const expandBtns = canvas.getAllByRole('button', { name: /^expand$/i }); await expect(expandBtns[1]).toHaveFocus(); }); // Space expands the second banner await userEvent.keyboard(' '); await wait(ANIMATION_DURATION); // Now the second banner has a Collapse button and it should have focus await waitFor(async () => { const secondCollapse = canvas.getByRole('button', { name: /^collapse$/i }); await expect(secondCollapse).toHaveFocus(); }); // Tab to the second banner's action button (now visible) await userEvent.tab(); await waitFor(async () => { const actionBtn = canvas.getByRole('button', { name: /^take action$/i }); await expect(actionBtn).toHaveFocus(); }); }, ...withVariantConfig(['mobile']), parameters: { ...withVariantConfig(['mobile']).parameters, viewport: { defaultViewport: 'mobile2', }, }, }; /** * CriticalBanner uses `aria-live="assertive"` to immediately announce content to screen readers. * Toggle the banner on/off and expand/collapse to hear how announcements change. */ export const LiveRegionAnnouncements: Story = { render: function Render() { const [visible, setVisible] = useState(false); const [expanded, setExpanded] = useState(false); return (
{visible && ( setExpanded(!expanded)} /> )}
); }, }; /** 400% zoom regression test with all variants. */ export const Zoom400: Story = { render: () => , ...withVariantConfig(['400%']), }; /** * Desktop force-expand test: verifies that banner is always expanded * when container width >= 768px, regardless of expanded prop value. */ export const DesktopForceExpand: Story = { render: function Render() { return (
); }, }; /** * Multi-line title animation test: verifies that animations work correctly * even when the title wraps to multiple lines on mobile. */ export const MultiLineTitleAnimation: Story = { render: function Render() { const [expanded, setExpanded] = useState(true); return ( setExpanded(!expanded)} /> ); }, ...withVariantConfig(['mobile']), }; /** * Internal state management test: verifies that the banner can manage its own * expanded state when onToggle is not provided (uncontrolled mode). */ export const UncontrolledState: Story = { render: function Render() { return (
); }, ...withVariantConfig(['mobile']), }; /** * Tests that clicking the toggle button works correctly in uncontrolled mode. * Verifies that the banner can expand/collapse without external state management. */ export const UncontrolledStateInteraction: Story = { render: function Render() { return ( ); }, play: async ({ canvasElement }) => { const canvas = within(canvasElement); // Wait for the collapse button to appear const collapseBtn = await canvas.findByRole('button', { name: /^collapse$/i }); // Click to collapse await userEvent.click(collapseBtn); await wait(ANIMATION_DURATION); // After collapsing, the button label changes to "Expand" const expandBtn = canvas.getByRole('button', { name: /^expand$/i }); await expect(expandBtn).toBeInTheDocument(); // Click to expand again await userEvent.click(expandBtn); await wait(ANIMATION_DURATION); // Should be back to "Collapse" const collapseBtnAgain = canvas.getByRole('button', { name: /^collapse$/i }); await expect(collapseBtnAgain).toBeInTheDocument(); }, ...withVariantConfig(['mobile']), parameters: { ...withVariantConfig(['mobile']).parameters, viewport: { defaultViewport: 'mobile2', }, }, }; export const RTLDiff: Story = { render: () => { const i18n = useRtlDiffI18n(); return ( <> } }} action={{ label: i18n.connectBank }} actionSecondary={{ label: i18n.learnMore }} /> ); }, ...withRTLDiff({ fixedRows: { heights: [10, 12, 12, 13, 13] }, renderAs: 'iframe', i18n: { titleOnly: { en: 'Title only', ar: 'العنوان فقط' }, titleOnlyDescription: { en: 'Description without actions or media.', ar: 'وصف بدون إجراءات أو وسائط.', }, withPrimaryAction: { en: 'With primary action', ar: 'مع إجراء رئيسي' }, withPrimaryActionDescription: { en: 'Banner with a single action button.', ar: 'لافتة تحتوي على زر إجراء واحد.', }, withBothActions: { en: 'With both actions', ar: 'مع كلا الإجراءين' }, withBothActionsDescription: { en: 'Banner with primary and secondary actions.', ar: 'لافتة تحتوي على إجراء رئيسي وإجراء ثانوي.', }, withMediaImage: { en: 'With media image', ar: 'مع صورة' }, withMediaImageDescription: { en: 'Banner with a custom image.', ar: 'لافتة تحتوي على صورة مخصصة.', }, withAvatarMedia: { en: 'With avatar media', ar: 'مع صورة رمزية' }, withAvatarMediaDescription: { en: 'Banner with an avatar icon.', ar: 'لافتة تحتوي على أيقونة رمزية.', }, verifyNow: { en: 'Verify now', ar: 'تحقّق الآن' }, learnMore: { en: 'Learn more', ar: 'اعرف المزيد' }, takeAction: { en: 'Take action', ar: 'اتخذ إجراءً' }, connectBank: { en: 'Connect bank', ar: 'ربط البنك' }, cardImage: { en: 'Wise card', ar: 'بطاقة Wise' }, }, }), };