Repository: raunofreiberg/axe-mode Branch: master Commit: 6305ac415ff4 Files: 19 Total size: 22.7 KB Directory structure: gitextract_xzzs6w27/ ├── .gitignore ├── LICENSE ├── README.md ├── example/ │ ├── .gitignore │ ├── .npmignore │ ├── index.html │ ├── index.tsx │ ├── package.json │ ├── styles.css │ └── tsconfig.json ├── package.json ├── src/ │ ├── axe-mode.tsx │ ├── icons.tsx │ ├── index.tsx │ └── styles.css ├── test/ │ └── blah.test.tsx ├── tsconfig.json ├── tsdx.config.js └── types/ └── index.d.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.log .DS_Store node_modules .cache dist ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2020 raunofreiberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # axe-mode ![npm](https://img.shields.io/npm/v/axe-mode?color=%236469FF) > WIP This project is an attempt to leverage [`axe-core`](https://github.com/dequelabs/axe-core) in a component to find accessibility violations and provide information on how to resolve them. Currently, this only works for React. [See it in action on CodeSandbox.](https://codesandbox.io/s/youthful-pare-oxtcc) ![Demo](https://i.gyazo.com/2eeb2f0bacbabfbe706932c545ec682c.gif) ## Usage Install the library: ```bash yarn add axe-mode -D ``` or ```bash npm install axe-mode --save-dev ``` Import the component and wrap it around your application or any other component tree you would like to validate: ```tsx import AxeMode from 'axe-mode'; function App() { return (

Hello world!

); } ``` Launch your application as usual. Any violations of accessibility will show up as an overlay. If you wish to interact with your application, overlays can be toggled on/off with Ctrl + I. You can safely leave the component around your application since [this whole library and its dependencies will be dropped in production.](https://github.com/raunofreiberg/axe-mode/blob/master/src/index.tsx#L7) **Note**: Make sure to only run in production by using the `disabled` prop with your environment variable. ================================================ FILE: example/.gitignore ================================================ .now ================================================ FILE: example/.npmignore ================================================ node_modules .cache dist ================================================ FILE: example/index.html ================================================ Playground
================================================ FILE: example/index.tsx ================================================ import 'react-app-polyfill/ie11'; import './styles.css'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import AxeMode from '../src/index'; function Subtitle() { return
Accessibility testing componentized
; } function Image() { const ref = React.useRef(null); React.useEffect(() => { // For testing whether violations from // DOM mutations are displayed. const id = setTimeout(() => { ref?.current?.setAttribute('alt', 'Avatar'); }, 3000); return () => clearTimeout(id); }, [ref]); return ( ); } const App = () => { return (

Axe Mode

); }; ReactDOM.render(, document.getElementById('root')); ================================================ FILE: example/package.json ================================================ { "name": "example", "version": "1.0.0", "main": "index.js", "license": "MIT", "scripts": { "start": "parcel index.html", "build": "parcel build index.html" }, "dependencies": { "react-app-polyfill": "^1.0.0" }, "alias": { "react": "../node_modules/react", "react-dom": "../node_modules/react-dom/profiling", "scheduler/tracing": "../node_modules/scheduler/tracing-profiling" }, "devDependencies": { "@types/react": "^16.9.11", "@types/react-dom": "^16.8.4", "parcel": "^1.12.3", "typescript": "^3.4.5" } } ================================================ FILE: example/styles.css ================================================ * { box-sizing: border-box; } body { margin: 0; height: 200vh; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; } .iconLink { display: inline-block; width: 24px; height: 24px; color: #222328; } header { display: flex; align-items: center; justify-content: space-between; background: white; height: 64px; padding: 0 32px; box-shadow: inset 0 -1px 0 0 #e6ebf4, 0 4px 8px 0 rgba(189, 192, 207, .08); } header img { border-radius: 50%; } input { height: 40px; padding: 8px 16px; margin: 0; border-radius: 4px; border: 1px solid #E6EBF4; appearance: none; font-size: 14px; background-color: #FAFAFC; color: #222328; } .login button { padding: 0 16px; background: #222328; height: 40px; margin: 0; border: 0; border-radius: 4px; color: white; font-weight: 500; text-transform: uppercase; font-size: 14px; cursor: pointer; width: 100%; } main { height: calc(100vh - 64px); display: flex; flex-direction: column; align-items: center; justify-content: center; } .login { display: grid; grid-gap: 16px; width: 300px; } .login h1, .login h6 { text-align: center; } .login h1, h6 { margin: 0; } h6 { color: #505366; line-height: 24px; } ================================================ FILE: example/tsconfig.json ================================================ { "compilerOptions": { "allowSyntheticDefaultImports": false, "target": "es5", "module": "commonjs", "jsx": "react", "moduleResolution": "node", "noImplicitAny": false, "noUnusedLocals": false, "noUnusedParameters": false, "removeComments": true, "strictNullChecks": true, "preserveConstEnums": true, "sourceMap": true, "lib": ["es2015", "es2016", "dom"], "baseUrl": ".", "types": ["node"] } } ================================================ FILE: package.json ================================================ { "version": "0.0.1-alpha.2", "license": "MIT", "main": "dist/index.js", "typings": "dist/index.d.ts", "files": [ "dist", "src" ], "engines": { "node": ">=10" }, "scripts": { "start": "tsdx watch", "build": "tsdx build", "test": "tsdx test --passWithNoTests", "lint": "tsdx lint", "prepare": "tsdx build" }, "peerDependencies": { "react": ">=16" }, "husky": { "hooks": { "pre-commit": "tsdx lint" } }, "prettier": { "printWidth": 80, "semi": true, "singleQuote": true, "trailingComma": "es5" }, "name": "axe-mode", "author": "raunofreiberg", "module": "dist/axe-mode.esm.js", "devDependencies": { "@types/react": "^16.9.34", "@types/react-dom": "^16.9.7", "husky": "^4.2.5", "react": "^16.13.1", "react-dom": "^16.13.1", "rollup-plugin-postcss": "^3.1.1", "tsdx": "^0.13.2", "tslib": "^1.11.1", "typescript": "^3.8.3" }, "dependencies": { "@reach/auto-id": "^0.10.1", "@reach/observe-rect": "^1.1.0", "@reach/popover": "^0.10.1", "axe-core": "^3.5.3" }, "eslintConfig": { "extends": "react-app", "overrides": [ { "files": [ "example/*" ], "rules": { "jsx-a11y/alt-text": 0, "jsx-a11y/anchor-is-valid": 0, "jsx-a11y/accessible-emoji": 0 } } ] }, "eslintIgnore": ["dist"] } ================================================ FILE: src/axe-mode.tsx ================================================ import './styles.css'; import * as React from 'react'; import axe, { ElementContext, Result } from 'axe-core'; import Popover from '@reach/popover'; import observeRect from '@reach/observe-rect'; import { IconMinor, IconModerate, IconSevere } from './icons'; type ViolationsByNode = Array<{ node: string; violations: Result[] }>; type AxeCoreModule = typeof axe; function getValidator(axe: AxeCoreModule) { return (node: ElementContext): Promise => { return new Promise((resolve, reject) => { axe.run(node, { reporter: 'v2' }, (error, results) => { if (error) reject(error); resolve(results.violations); }); }); }; } // Copied from: // https://stackoverflow.com/questions/29321742/react-getting-a-component-from-a-dom-element-for-debugging // ¯\_(ツ)_/¯ function getComponentFromNode(node: HTMLElement): string { const [component] = Object.keys(node) .filter(key => key.startsWith('__reactInternalInstance$')) .map((key: string) => { const fiberNode = (node as any)[key]; const component = fiberNode && fiberNode._debugOwner; return component.type.displayName || component.type.name; }); return component; } function segmentViolationsByNode(violations: Result[]): ViolationsByNode { // Find all DOM nodes affected by the violations const nodes = violations.flatMap(violation => violation.nodes.flatMap(node => node.target) ); // Based on the found nodes, find all violations that they caused return nodes.map(node => { const violationsByNode = violations.filter(violation => violation.nodes.some(n => n.target.includes(node)) ); return { node, violations: violationsByNode, }; }); } function setOverlayPosition( overlayNode: HTMLElement, { width, height, x, y }: DOMRect ) { overlayNode.style.setProperty('width', `${width}px`); overlayNode.style.setProperty('height', `${height}px`); overlayNode.style.setProperty('left', `${x}px`); overlayNode.style.setProperty('top', `${y}px`); } function Violation({ target, violations, }: { target: any; violations: Result[]; }) { const [open, setOpen] = React.useState(false); const targetRef = React.useRef(null); const popoverRef = React.useRef(null); const overlayRef = React.useRef(null); function toggle() { setOpen(prevOpen => !prevOpen); } function close() { setOpen(false); } React.useEffect(() => { const targetNode = document.querySelector(target); const overlayNode = document.createElement('axe-mode-overlay'); targetRef.current = targetNode; overlayRef.current = overlayNode; const { observe, unobserve } = observeRect(targetNode, targetRect => { setOverlayPosition(overlayNode, targetRect); }); const bounds = targetNode.getBoundingClientRect(); setOverlayPosition(overlayNode, bounds); observe(); document.body.appendChild(overlayNode); overlayNode.addEventListener('mousedown', toggle); return () => { unobserve(); document.body.removeChild(overlayNode); overlayNode.removeEventListener('mousedown', toggle); }; }, [target]); React.useEffect(() => { function listener(e: MouseEvent) { const eventTarget = e.target as Node; const isTargetInPopover = eventTarget === overlayRef.current || popoverRef.current?.contains(eventTarget); if (!isTargetInPopover) { close(); } } if (open) { document.addEventListener('mousedown', listener); } return () => { document.removeEventListener('mousedown', listener); }; }, [open, target]); if (!open) { return null; } return (

Accessibility violation

{getComponentFromNode(document.querySelector(target)) || target} {violations.map(violation => { const [{ any, all }] = violation.nodes.filter(node => node.target.includes(target) ); return (
{violation.impact === 'minor' ? ( ) : violation.impact === 'moderate' ? ( ) : ( )}

{violation.help}

{!!all.length && ( <> Fix all of the following:
    {all.map(check => (
  • {check.message}
  • ))}
)} {!!any.length && ( <> Fix any of the following:
    {any.map(check => (
  • {check.message}
  • ))}
)}
); })}
); } export interface AxeModeProps { children: React.ReactElement | React.ReactElement[]; disabled?: boolean; } export default function AxeModeImpl({ children, disabled }: AxeModeProps) { const [violations, setViolations] = React.useState([]); const [interactive, setInteractive] = React.useState(false); const idleId = React.useRef(null); const childrenRef = React.useRef(null); React.useEffect(() => { if (disabled || interactive || !childrenRef.current) { return; } if (idleId.current && 'cancelIdleCallback' in window) { window.cancelIdleCallback(idleId.current); idleId.current = null; } function getViolations() { const validateNode = getValidator(axe); validateNode(childrenRef.current as ElementContext).then(setViolations); } function callback() { // Safari does not support requestIdleCallback 😔 if ('requestIdleCallback' in window) { idleId.current = window.requestIdleCallback(getViolations); } else { getViolations(); } } const observer = new MutationObserver(callback); // We need to run this once so we don't wait for // DOM mutations to display the violations. callback(); observer.observe(childrenRef.current, { attributes: true, childList: true, subtree: true, }); return () => { if (idleId.current && 'cancelIdleCallback' in window) { window.cancelIdleCallback(idleId.current); idleId.current = null; } observer.disconnect(); }; }, [disabled, interactive]); React.useEffect(() => { function listener(e: KeyboardEvent) { if (e.ctrlKey && e.key === 'i') { setInteractive(!interactive); } } document.addEventListener('keydown', listener); return () => { document.removeEventListener('keydown', listener); }; }, [interactive]); const violationsByNode = segmentViolationsByNode(violations); if (disabled || interactive) { return <>{children}; } console.log(violationsByNode); return ( <> {children} {violationsByNode.map(({ node, violations }, index) => ( ))} ); } ================================================ FILE: src/icons.tsx ================================================ import * as React from 'react'; import { useId } from '@reach/auto-id'; export const IconMinor: React.FC, 'viewBox' >> = props => { const titleId = `minor-icon-${useId(props.id)}`; return ( Minor impact ); }; export const IconModerate: React.FC, 'viewBox' >> = props => { const titleId = `moderate-icon-${useId(props.id)}`; return ( Moderate impact ); }; export const IconSevere: React.FC, 'viewBox' >> = props => { const titleId = `severe-icon-${useId(props.id)}`; return ( Severe impact ); }; ================================================ FILE: src/index.tsx ================================================ import * as React from 'react'; import { AxeModeProps } from './axe-mode'; const AxeMode = React.lazy(() => import('./axe-mode')); export default function Loader(props: AxeModeProps) { if (process.env.NODE_ENV === 'development') { return ( ); } return {props.children}; } export { AxeModeProps }; ================================================ FILE: src/styles.css ================================================ @keyframes slideDown { 0% { opacity: 0; transform: translateY(-8px); } 100% { opacity: 1; transform: translateY(0); } } axe-mode-overlay { position: fixed; background: rgba(255, 91, 91, 0.2); border: 1px solid rgb(255, 91, 91); border-radius: 4px; cursor: pointer; } .popover { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; position: absolute; border-radius: 4px; box-shadow: 0 2px 8px 0 rgba(189, 192, 207, 0.16); border: 1px solid #E6EBF4; background-color: white; padding: 16px; margin: 8px 0; z-index: 1337; animation: slideDown 0.4s cubic-bezier(.2, .8, .4, 1); } .popover h2 { margin: 0; font-size: 20px; color: #222328; } .popover ul { padding-left: 14px; margin-top: 8px; margin-bottom: 0; list-style-type: '・ '; } .popover li { padding: 0; max-width: 40ch; margin: 8px 0 0 0; font-size: 14px; color: #505366; } .popover small { display: block; font-size: 12px; color: #BDC0CF; margin: 4px 0 8px 0; } .popover h2 { max-width: 40ch; } .popover a { color: #6469FF; } .popover code { font-size: 12px; line-height: 20px; padding-left: 5px; padding-right: 5px; background-color: rgba(100, 105, 255, 0.05); color: #6469FF; border-radius: 3px; } .popover .checks { margin-top: 16px; } .popover .checks .header { display: flex; font-size: 1.2rem; margin: 0.5em 0; align-items: center; } .popover .checks .header svg { width: 1em; height: 1em; margin-right: 0.325em; } .popover .checks .header h3 { font-size: 1em; margin: 0; } .controls { display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px; } .close { width: 24px; height: 24px; border: 0; background: none; padding: 0; margin: 0; cursor: pointer; } ================================================ FILE: test/blah.test.tsx ================================================ import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Thing } from '../src'; describe('it', () => { it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(, div); ReactDOM.unmountComponentAtNode(div); }); }); ================================================ FILE: tsconfig.json ================================================ { "include": ["src", "types"], "compilerOptions": { "module": "esnext", "lib": ["dom", "esnext"], "importHelpers": true, "declaration": true, "sourceMap": true, "rootDir": "./src", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "moduleResolution": "node", "baseUrl": "./", "paths": { "*": ["src/*", "node_modules/*"] }, "jsx": "react", "esModuleInterop": true } } ================================================ FILE: tsdx.config.js ================================================ const postcss = require('rollup-plugin-postcss'); const path = require('path'); module.exports = { rollup(config, options) { config.plugins = [postcss(), ...config.plugins]; // To get code splitting to work, we need to set output.dir instead of // output.file, which is what TSDX does by default const { file, ...output } = config.output || {}; config.output = { ...output, dir: path.join(__dirname, 'dist'), }; return config; }, }; ================================================ FILE: types/index.d.ts ================================================ type RequestIdleCallbackOptions = { timeout: number; }; type RequestIdleCallbackDeadline = { readonly didTimeout: boolean; timeRemaining: () => number; }; declare global { // tsdx supports this out of the box, can be useful for omitting unused code // from the prod bundle. const __DEV__: boolean; interface Window { requestIdleCallback: ( callback: (deadline: RequestIdleCallbackDeadline) => void, opts?: RequestIdleCallbackOptions ) => number; cancelIdleCallback: (handle: number) => void; } } export {};