Socket
Socket
Sign inDemoInstall

@storybook/addon-a11y

Package Overview
Dependencies
2
Maintainers
11
Versions
1701
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @storybook/addon-a11y

Test component compliance with web accessibility standards


Version published
Weekly downloads
1.8M
increased by1.23%
Maintainers
11
Install size
2.71 MB
Created
Weekly downloads
 

Package description

What is @storybook/addon-a11y?

The @storybook/addon-a11y package is an addon for Storybook that helps you improve the accessibility of your UI components. It integrates with Storybook to provide automated checks and manual testing tools for accessibility issues, allowing developers to ensure their components are accessible to as many users as possible.

What are @storybook/addon-a11y's main functionalities?

Automated accessibility checks

Automatically run accessibility checks on your components within the Storybook UI. It uses the axe-core library to test each component for accessibility issues and provides a report.

import { withA11y } from '@storybook/addon-a11y';

export default {
  title: 'Button',
  decorators: [withA11y],
};

export const AccessibleButton = () => <button>Click me</button>;
export const InAccessibleButton = () => <button style={{ color: 'white', backgroundColor: 'white' }}>Can't see me</button>;

Manual accessibility testing tools

Provides tools for manual accessibility testing, such as color contrast checkers and keyboard event simulation, to complement the automated checks.

N/A

Customizable rules

Allows customization of the accessibility rules used for testing, enabling or disabling specific rules to tailor the checks to your project's needs.

import { withA11y } from '@storybook/addon-a11y';

export default {
  title: 'Button',
  decorators: [withA11y],
  parameters: {
    a11y: {
      config: {
        rules: [{ id: 'color-contrast', enabled: false }]
      }
    }
  }
};

Other packages similar to @storybook/addon-a11y

Changelog

Source

8.1.0

Storybook 8.1 is here with a tone of new features and bug fixes:

  • 🏷️ Static tag-based filtering
  • 🦺 Type-safe, standards-based module mocking
  • 🐣 New beforeEach test hook
  • 🧳 Portable Stories API for Playwright Component Testing
  • 🐕‍🦺 Support the new signal-based input & output functions in Angular
  • 2️⃣ Two new ways to create stories: generating them from story controls or from your components directly!
<details> <summary>List of all updates</summary>
  • Addon-actions: Fix falsy args printing as object - 22163 - #26917, thanks @Fatcat560!
  • Addon-docs: Fix MDX compilation with @vitejs/plugin-react-swc and plugins - #26837, thanks @JReinhold!
  • Addon-docs: Fix providerImportSource extension - #26868, thanks @bashmish!
  • Addon-docs: Fix react-dom/server imports breaking stories and docs - #26557, thanks @JReinhold!
  • Addon-docs: Support Stencil based display names in source snippets - #26592, thanks @yannbf!
  • Addon-docs: Fix [Object object] displayName in some JSX components - #26566, thanks @yannbf!
  • Angular: Add type support for Angular's input signals - #26413, thanks @valentinpalkovic!
  • Angular: Add type support for Angular's output signals - #26546, thanks @valentinpalkovic!
  • API: Add API access to sidebar renderLabel - #27099, thanks @shilman!
  • Args: Add possibility to mark controls as read-only - #26577, thanks @valentinpalkovic!
  • Automigrations: Fix name of VTA addon - #26816, thanks @valentinpalkovic!
  • Automigrations: Add migration note about new react-docgen default - #26620, thanks @valentinpalkovic!
  • Automigrations: Fix missing support for mts vite config - #26441, thanks @drik98!
  • Automigrations: Improve react-docgen automigration prompt - #27106, thanks @valentinpalkovic!
  • Blocks: Add of prop to Subtitle - #22552, thanks @joaonunomota!
  • Blocks: Add of prop to Title - #23728, thanks @Sidnioulz!
  • CLI: Add --config-dir flag to add command - #26771, thanks @eric-blue!
  • CLI: Add --config-dir flag to migrate command - #26721, thanks @yannbf!
  • CLI: Add main.js docs.autodocs automigration - #27089, thanks @shilman!
  • CLI: Add Visual Tests addon install auto-migration when upgrading to 8.0.x - #26766, thanks @ndelangen!
  • CLI: Automigrate improve upgrade storybook related packages - #26497, thanks @ndelangen!
  • CLI: Automigrations copy edits - #26342, thanks @joevaugh4n!
  • CLI: Fix eslint configuration for string extends - #27097, thanks @shilman!
  • CLI: Improve Yarn berry error parsing - #26616, thanks @yannbf!
  • CLI: Improve vite-config-file.ts - #26375, thanks @joevaugh4n!
  • CLI: Instruct the correct auto-migration command - #26515, thanks @ndelangen!
  • CLI: Introduce package manager fallback for initializing Storybook in an empty directory with yarn1 - #26500, thanks @valentinpalkovic!
  • CLI: Throw an error when running upgrade command in incorrect cwd - #26585, thanks @yannbf!
  • Codemods: Escape filename given as argument - #26430, thanks @YukiKitagata!
  • Controls: Add Channels API to search for files in the project root - #26726, thanks @valentinpalkovic!
  • Controls: Added server channel to create a new story - #26769, thanks @valentinpalkovic!
  • Controls: Add UI to create new story files - #26875, thanks @valentinpalkovic!
  • Controls: Fix crashing when docgen extraction partially fails - #26862, thanks @yannbf!
  • Controls: Fix disable condition in ArgControl component - #26567, thanks @valentinpalkovic!
  • Controls: Fix number controls do not reset - #26372, thanks @jiyiru!
  • Core: Add duration and onClick support to Notification API and improve Notification UI - #26696, thanks @ghengeveld!
  • Core: Drop unneeded UPDATE_STORY_ARGS which was for SSv6 - #25993, thanks @tmeasday!
  • Core: Ensure that simultaneous onStoriesChanged don't clobber each other - #26882, thanks @tmeasday!
  • Core: Fix filters not being applied in WebKit - #26949, thanks @JReinhold!
  • Core: Fix preloading too early - #26442, thanks @ndelangen!
  • Core: Implement file formatter - #26809, thanks @valentinpalkovic!
  • Core: Optimize clearNotification - #26415, thanks @ndelangen!
  • Core: Save from controls - #26827, thanks @ndelangen!
  • CSF: Allow default export without title or component attributes - #26516, thanks @kasperpeulen!
  • CSF: Fix typings for control and other properties of argTypes - #26824, thanks @kasperpeulen!
  • CSF: Make sure loaders/decorators can be used as array - #26514, thanks @kasperpeulen!
  • Dependencies: Upgrade @storybook/csf to 0.1.5 - #26958, thanks @Cherry!
  • Dependencies: Upgrade @joshwooding/vite-plugin-react-docgen-typescript to 0.3.1 - #26673, thanks @joshwooding!
  • Dependencies: Upgrade ejs to 3.1.10 - #27054, thanks @RiuSalvi!
  • Dependencies: Bump es-module-lexer - #26737, thanks @valentinpalkovic!
  • Dependencies: Update globby dependency - #26733, thanks @valentinpalkovic!
  • Dependencies: Update postcss-loader in Next.js framework - #26707, thanks @valentinpalkovic!
  • Doc Tools: Signature Type Error Handling - #26774, thanks @ethriel3695!
  • Indexer: Escape special characters in storyImport regex - #22545, thanks @VojGin!
  • Maintenance: Fix performance regressions - #26411, thanks @kasperpeulen!
  • MDX: Do not transform http:// links - #26488, thanks @JReinhold!
  • Next.js: Fix Compatibility with <v14.0.4 - #27082, thanks @JReinhold!
  • Next.js: Fix next/font usage on Windows machines - #26700, thanks @valentinpalkovic!
  • Next.js: Move sharp into optional deps - #26787, thanks @shuta13!
  • Next.js: Support v14.2 useParams functionality - #26874, thanks @yannbf!
  • Next.js: Implement next redirect and the RedirectBoundary - #27050, thanks @yannbf!
  • Next.js: Support path aliases when no base url is set - #26651, thanks @yannbf!
  • Node: Safe use of document for preview - #24248, thanks @DylanPiercey!
  • Onboarding: Improve UI - #27074, thanks @ndelangen!
  • Portable stories: Introduce experimental Playwright CT API and Support for more renderers - #26063, thanks @yannbf!
  • Portable stories: Make setProjectAnnotations accept multiple types of imports - #26316, thanks @yannbf!
  • Portable Stories: Remove link to missing docs - #27075, thanks @JReinhold!
  • Portable Stories: Warn when rendering stories without cleaning up first - #27008, thanks @JReinhold!
  • React-Docgen: Make sure to be able to handle empty unions - #26639, thanks @kasperpeulen!
  • React: Support v19 betas in peer dependencies - #26960, thanks @JReinhold!
  • React: Support v19 in react-dom-shim - #26898, thanks @Tobbe!
  • Tags: Add project tags, negation, dev/autodocs/test system tags - #26634, thanks @shilman!
  • Tags: Fix missing default tags if no preview.js - #27098, thanks @shilman!
  • Test: Add @storybook/test as dev dependency - #26458, thanks @arnabsen!
  • Test: Make spies reactive so that they can be logged by addon-actions - #26740, thanks @kasperpeulen!
  • Test: Remove chai as dependency of @storybook/test - #26852, thanks @kasperpeulen!
  • Test: Support module mocking with conditional subpath imports in package.json - #26688, thanks @kasperpeulen!
  • Theming: Update emotion dependencies - #26623, thanks @SimenB!
  • Typescript: Add types for experimental-playwright entries without type:bundler - #27107, thanks @ndelangen!
  • UI: Add key property to list children in Highlight component - #26471, thanks @valentinpalkovic!
  • UI: Fix not re-rendering tabs on state change - #26899, thanks @lifeiscontent!
  • UI: Fix panel layout resizing do not apply when done too fast - #26460, thanks @jorge-ji!
  • UI: Fix search result color contrast - #26287, thanks @winchesHe!
  • UI: Fix sidebar search hanging when selecting a story in touch mode - #26807, thanks @JReinhold!
  • UI: Fix theming of elements inside bars - #26527, thanks @valentinpalkovic!
  • UI: Improve empty state of addon panel - #26481, thanks @yannbf!
  • UI: Replace the icon prop in the Manager API - #26477, thanks @cdedreuille!
  • Viewport: Fix missing style - #26530, thanks @jpzwarte!
  • Vite: Merge assetsInclude property with Storybook default values - #26860, thanks @yuemori!
  • Vue: Disable controls for events, slots, and expose - #26751, thanks @shilman!
  • Webpack: Bump webpack-dev-middleware to patch high security issue - #26655, thanks @jwilliams-met!
  • Webpack: Fix sourcemap generation in webpack react-docgen-loader - #26676, thanks @valentinpalkovic!
  • Webpack: Hide runtime errors - #23175, thanks @donaldpipowitch!
</details>

Readme

Source

storybook-addon-a11y

This Storybook addon can be helpful to make your UI components more accessible.

Framework Support

Screenshot

Getting started

First, install the addon.

$ yarn add @storybook/addon-a11y --dev

Add this line to your main.js file (create this file inside your Storybook config directory if needed).

export default {
  addons: ['@storybook/addon-a11y'],
};

And here's a sample story file to test the addon:

import React from 'react';

export default {
  title: 'button',
};

export const Accessible = () => <button>Accessible button</button>;

export const Inaccessible = () => (
  <button style={{ backgroundColor: 'red', color: 'darkRed' }}>Inaccessible button</button>
);

Handling failing rules

When Axe reports accessibility violations in stories, there are multiple ways to handle these failures depending on your needs.

Story-level overrides

At the Story level, override rules using parameters.a11y.config.rules.

export const InputWithoutAutofill = () => <input type="text" autocomplete="nope" />;

InputWithoutAutofill.parameters = {
  a11y: {
    // Avoid doing this, as it will fully disable all accessibility checks for this story.
    disable: true,

    // Instead, override rules 👇
    // axe-core configurationOptions (https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#parameters-1)
    config: {
      rules: [
        {
          // You can exclude some elements from failing a specific rule:
          id: 'autocomplete-valid',
          selector: '*:not([autocomplete="nope"])',
        },
        {
          // You can also signify that a violation will need to be fixed in the future
          // by overriding the result of a rule to return "Needs Review"
          // rather than "Violation" if the rule fails:
          id: 'landmark-complementary-is-top-level',
          reviewOnFail: true,
        },
      ],
    },
  },
};

Alternatively, you can disable specific rules in a Story:

export const Inaccessible = () => (
  <button style={{ backgroundColor: 'red', color: 'darkRed' }}>Inaccessible button</button>
);
Inaccessible.parameters = {
  a11y: {
    config: {
      rules: [{ id: 'color-contrast', enabled: false }],
    },
  },
};

Tip: clearly explain in a comment why a rule was overridden, it’ll help you and your team trace back why certain violations aren’t being reported or need to be addressed. For example:

MyStory.parameters = {
  a11y: {
    config: {
      rules: [
        {
          // Allow `autocomplete="nope"` on form elements,
          // a workaround to disable autofill in Chrome.
          // @link https://bugs.chromium.org/p/chromium/issues/detail?id=468153
          id: 'autocomplete-valid',
          selector: '*:not([autocomplete="nope"])',
        },
        {
          // @fixme Color contrast of subdued text fails, as raised in issue #123.
          id: 'color-contrast',
          reviewOnFail: true,
        },
      ],
    },
  },
};

Global overrides

When you want to ignore an accessibility rule or change its settings across all stories, set parameters.a11y.config.rules in your Storybook’s preview.ts file. This can be particularly useful for ignoring false positives commonly reported by Axe.

// .storybook/preview.ts

export const parameters = {
  a11y: {
    config: {
      rules: [
        {
          // This tells Axe to run the 'autocomplete-valid' rule on selectors
          // that match '*:not([autocomplete="nope"])' (all elements except [autocomplete="nope"]).
          // This is the safest way of ignoring a violation across all stories,
          // as Axe will only ignore very specific elements and keep reporting
          // violations on other elements of this rule.
          id: 'autocomplete-valid',
          selector: '*:not([autocomplete="nope"])',
        },
        {
          // To disable a rule across all stories, set `enabled` to `false`.
          // Use with caution: all violations of this rule will be ignored!
          id: 'autocomplete-valid',
          enabled: false,
        },
      ],
    },
  },
};

Disabling checks

If you wish to entirely disable a11y checks for a subset of stories, you can control this with story parameters:

export const MyNonCheckedStory = () => <SomeComponent />;
MyNonCheckedStory.parameters = {
  // Avoid doing this, as it fully disables all accessibility checks for this story,
  // and consider the techniques described above.
  a11y: { disable: true },
};

Parameters

For more customizability use parameters to configure aXe options. You can override these options at story level too.

import React from 'react';
import { storiesOf, addDecorator, addParameters } from '@storybook/react';

export default {
  title: 'button',
  parameters: {
    a11y: {
      // optional selector which element to inspect
      element: '#storybook-root',
      // axe-core configurationOptions (https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#parameters-1)
      config: {},
      // axe-core optionsParameter (https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter)
      options: {},
      // optional flag to prevent the automatic check
      manual: true,
    },
  },
};

export const accessible = () => <button>Accessible button</button>;

export const inaccessible = () => (
  <button style={{ backgroundColor: 'red', color: 'darkRed' }}>Inaccessible button</button>
);

Automate accessibility tests with test runner

The test runner does not apply any rules that you have set on your stories by default. You can configure the runner to correctly apply the rules by following the guide on the Storybook docs.

Roadmap

  • Make UI accessible
  • Show in story where violations are.
  • Add more example tests
  • Add tests
  • Make CI integration possible

Keywords

FAQs

Last updated on 14 May 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc