├── .changeset └── config.json ├── .eslintrc.cjs ├── .github ├── dependabot.yml └── workflows │ ├── CI.yml │ ├── dependabot-auto-merge.yml │ └── release.yml ├── .gitignore ├── .prettierrc ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── package-lock.json ├── package.json ├── src ├── apca-bronze.ts ├── apca-silver-plus.ts ├── index.test.ts └── index.ts ├── tsconfig.json └── web-test-runner.config.mjs /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json", 3 | "changelog": [ 4 | "@changesets/changelog-github", 5 | { "repo": "StackExchange/apca-check" } 6 | ], 7 | "commit": false, 8 | "access": "public", 9 | "baseBranch": "main" 10 | } 11 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: "@typescript-eslint/parser", 4 | plugins: ["@typescript-eslint", "prettier"], 5 | extends: [ 6 | "eslint:recommended", 7 | "plugin:@typescript-eslint/recommended", 8 | "prettier", 9 | ], 10 | rules: { 11 | "prettier/prettier": "error", 12 | }, 13 | }; 14 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "npm" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | versioning-strategy: increase -------------------------------------------------------------------------------- /.github/workflows/CI.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | build-and-test: 11 | name: Build and Test 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: ⬇️ Checkout 15 | uses: actions/checkout@v3 16 | 17 | - name: ⎔ Setup node 18 | uses: actions/setup-node@v3 19 | with: 20 | node-version: 'lts/*' 21 | 22 | - name: 🏗 Install and Build 23 | run: | 24 | npm ci 25 | npx playwright install --with-deps 26 | npm run build 27 | 28 | - name: ▶️ Linting 29 | run: npm run lint 30 | 31 | - name: ▶️ Testing 32 | run: npm run test 33 | 34 | # cancel the jobs if another workflow is kicked off for the same branch 35 | concurrency: 36 | group: ${{ github.workflow }}-${{ github.ref }} 37 | cancel-in-progress: true -------------------------------------------------------------------------------- /.github/workflows/dependabot-auto-merge.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot auto-merge 2 | on: pull_request 3 | 4 | permissions: 5 | contents: write 6 | pull-requests: write 7 | 8 | jobs: 9 | dependabot: 10 | runs-on: ubuntu-latest 11 | if: github.actor == 'dependabot[bot]' 12 | steps: 13 | - name: Dependabot metadata 14 | id: metadata 15 | uses: dependabot/fetch-metadata@v1 16 | with: 17 | github-token: "${{ secrets.GITHUB_TOKEN }}" 18 | - name: Enable auto-merge for Dependabot PRs 19 | if: steps.metadata.outputs.update-type == 'version-update:semver-minor' || steps.metadata.outputs.update-type == 'version-update:semver-patch' 20 | run: gh pr merge --auto --squash "$PR_URL" 21 | env: 22 | PR_URL: ${{github.event.pull_request.html_url}} 23 | GH_TOKEN: ${{secrets.GITHUB_TOKEN}} 24 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | workflow_run: 5 | workflows: 6 | - CI 7 | branches: 8 | - main 9 | types: 10 | - completed 11 | 12 | jobs: 13 | release: 14 | name: Release 15 | # run only if the CI workflow is successful 16 | if: ${{ github.event.workflow_run.conclusion == 'success' }} 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: ⬇️ Checkout 20 | uses: actions/checkout@v3 21 | # make sure to checkout the commit that triggered the CI workflow 22 | # (which is not necessarily the latest commit) 23 | with: 24 | ref: ${{ github.event.workflow_run.head_commit.id }} 25 | 26 | - name: ⎔ Setup node 27 | uses: actions/setup-node@v3 28 | with: 29 | node-version: 'lts/*' 30 | 31 | - name: 🏗 Install and Build 32 | run: | 33 | npm ci 34 | npm run build 35 | 36 | - name: 🚀 Create/Update Release Pull Request or Publish to npm 37 | id: changesets 38 | uses: changesets/action@v1 39 | with: 40 | publish: npm run release 41 | title: 'chore(new-release)' 42 | commit: 'chore(new-release)' 43 | env: 44 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 45 | NPM_TOKEN: ${{ secrets.NPM_API_KEY }} 46 | 47 | # cancel the jobs if another workflow is kicked off for the same branch 48 | concurrency: 49 | group: ${{ github.workflow }}-${{ github.ref }} 50 | cancel-in-progress: true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .idea 4 | .DS_Store -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "semi": true, 4 | "singleQuote": false, 5 | "quoteProps": "consistent", 6 | "printWidth": 80, 7 | "endOfLine": "auto" 8 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # apca-check 2 | 3 | ## 0.1.1 4 | 5 | ### Patch Changes 6 | 7 | - [#132](https://github.com/StackExchange/apca-check/pull/132) [`90ca26a`](https://github.com/StackExchange/apca-check/commit/90ca26ac7f5fd93ad61d4184936ba7d13440417d) Thanks [@MatteoPieroni](https://github.com/MatteoPieroni)! - fix: bug with array reversal 8 | 9 | ## 0.1.0 10 | 11 | ### Minor Changes 12 | 13 | - [`a88c8f6`](https://github.com/StackExchange/apca-check/commit/a88c8f67b6f428af6a6280fcbae074eb47f668c0) Thanks [@giamir](https://github.com/giamir)! - Rename package to `apca-check` to comply with Deque Systems, Inc. request (https://github.com/StackExchange/axe-apca/issues/8). 14 | 15 | BREAKING CHANGE: The [`axe-apca`](https://www.npmjs.com/package/axe-apca) package is now **deprecated**. 16 | Please remove it from your dependencies and use [`apca-check`](https://www.npmjs.com/package/apca-check) instead. 17 | For more information on installation and usage consult the [README.md](https://github.com/StackExchange/apca-check). 18 | 19 | ## 0.0.4 20 | 21 | ### Patch Changes 22 | 23 | - [`95e3a68`](https://github.com/StackExchange/apca-check/commit/95e3a68c581d6c54e7ec8d54ba5a5534943665e7) Thanks [@giamir](https://github.com/giamir)! - Compile distribution files so that they are compatible with node.js versions supporting ecmascript modules 24 | 25 | - [`1e300c6`](https://github.com/StackExchange/apca-check/commit/1e300c64de3d67798d4ee3214da61a102d699cd3) Thanks [@giamir](https://github.com/giamir)! - Fix typo in rules messages 26 | 27 | ## 0.0.3 28 | 29 | ### Patch Changes 30 | 31 | - [`42d5b12`](https://github.com/StackExchange/apca-check/commit/42d5b12035bfea11c37346613e6f8d91225bb80f) Thanks [@giamir](https://github.com/giamir)! - Fix package.json metadata 32 | 33 | ## 0.0.2 34 | 35 | ### Patch Changes 36 | 37 | - [`ccf1e94`](https://github.com/StackExchange/apca-check/commit/ccf1e94bc1c8c231667fd84d943b2065cf6283fb) Thanks [@giamir](https://github.com/giamir)! - Typescript support for moduleResolution < node16 38 | 39 | ## 0.0.1 40 | 41 | ### Patch Changes 42 | 43 | - [`7728604`](https://github.com/StackExchange/apca-check/commit/7728604acb78e886ce4b7989a1cf916354c167b2) Thanks [@giamir](https://github.com/giamir)! - Initial release 44 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright 2023 Stack Exchange Inc. 4 | 5 | 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: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | 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. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # apca-check 2 | 3 | [![ci status][gh-action-badge]][gh-action-url] [![npm version][npm-badge]][npm-url] 4 | 5 | This package contains custom axe rules and checks for [APCA](https://readtech.org/) Bronze and Silver+ [conformance levels](https://readtech.org/ARC/tests/visual-readability-contrast/?tn=criterion). 6 | 7 | ## Usage 8 | 9 | ### Installation 10 | 11 | ```bash 12 | npm install --save-dev axe-core apca-check 13 | ``` 14 | 15 | ### Setup 16 | 17 | ```js 18 | import axe from "axe-core"; 19 | import { registerAPCACheck } from 'apca-check'; 20 | 21 | registerAPCACheck('bronze'); // or registerAPCACheck('silver'); 22 | 23 | // consider turning off default WCAG 2.2 AA color contrast rules when using APCA 24 | axe.configure({ 25 | rules: [{ id: "color-contrast", enabled: false }] 26 | }) 27 | 28 | axe.run(document, (err, results) => { 29 | if (err) throw err; 30 | console.log(results); 31 | }); 32 | ``` 33 | 34 | ### Using custom APCA thresholds 35 | 36 | To set custom thresholds for APCA checks, follow these steps: 37 | 38 | 1. Use `custom` as the first argument when calling `registerAPCACheck`. 39 | 1. Provide a function as the second argument, optionally accepting `fontSize` and `fontWeight` arguments. 40 | 41 | 42 | ```js 43 | const customConformanceThresholdFn = (fontSize, fontWeight) => { 44 | const size = parseFloat(fontSize); 45 | const weight = parseFloat(fontWeight); 46 | 47 | return size >= 32 || weight > 700 ? 45 : 60; 48 | }; 49 | 50 | registerAPCACheck('custom', customConformanceThresholdFn); 51 | ``` 52 | 53 | ## Development 54 | 55 | ### Prerequisites 56 | 57 | - Node.js v18+ 58 | 59 | ### Linting 60 | To run eslint (including prettier as a formatter) you can run 61 | ``` 62 | npm run lint 63 | ``` 64 | To have eslint fix any autofixable issue run 65 | ``` 66 | npm run lint:fix 67 | ``` 68 | 69 | ### Testing 70 | 71 | Tests are run by web-test-runner in combination with playwright against chromium, firefox and webkit 72 | 73 | ``` 74 | npm run test 75 | ``` 76 | 77 | For watch mode 78 | ``` 79 | npm run test:watch 80 | ``` 81 | 82 | ### Publishing 83 | 84 | We use [changesets](https://github.com/changesets/changesets) to automatize the steps necessary to publish to NPM, create GH releases and a changelog. 85 | 86 | - Every time you do work that requires a new release to be published, [add a changesets entry](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md) by running `npx chageset` and follow the instrcutions on screen. (changes that do not require a new release - e.g. changing a test file - don't need a changeset). 87 | - When opening a PR without a corresponding changeset the [changesets-bot](https://github.com/apps/changeset-bot) will remind you to do so. It generally makes sense to have one changeset for PR (if the PR changes do not require a new release to be published the bot message can be safely ignored) 88 | - The [release github workflow](.github/workflows/release.yml) continuosly check if there are new pending changesets in the main branch, if there are it creates a GH PR (`chore(release)` [see example](https://github.com/StackExchange/apca-check/pull/2)) and continue updating it as more changesets are potentially pushed/merged to the main branch. 89 | - When we are ready to cut a release we need to simply merge the `chore(release)` PR back to main and the release github workflow will take care of publishing the changes to NPM and create a GH release for us. The `chore(release)` PR also give us an opportunity to adjust the automatically generated changelog when necessary (the entry in the changelog file is also what will end up in the GH release notes). 90 | 91 | _The release github workflow only run if the CI workflow (running linter, formatter and tests) is successful: CI is blocking accidental releases_. 92 | 93 | _Despite using changesets to communicate the intent of creating releases in a more explicit way, we still follow [conventional commits standards](https://www.conventionalcommits.org/en/v1.0.0/) for keeping our git history easily parseable by the human eye._ 94 | 95 | ## License 96 | Copyright 2023 Stack Exchange, Inc and released under the [MIT License](/LICENSE.MD). 97 | `axe-core®` and `axe®` are a trademark of Deque Systems, Inc. in the US and other countries. 98 | 99 | 100 | [gh-action-url]: https://github.com/StackExchange/apca-check/actions/workflows/CI.yml 101 | [gh-action-badge]: https://github.com/StackExchange/apca-check/actions/workflows/CI.yml/badge.svg?branch=main 102 | [npm-url]: https://npmjs.org/package/apca-check 103 | [npm-badge]: https://img.shields.io/npm/v/apca-check.svg -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "apca-check", 3 | "description": "Axe rules to check against APCA bronze and silver+ conformance levels.", 4 | "version": "0.1.1", 5 | "type": "module", 6 | "types": "./dist/index.d.ts", 7 | "module": "./dist/index.js", 8 | "exports": { 9 | ".": { 10 | "types": "./dist/index.d.ts", 11 | "import": "./dist/index.js" 12 | } 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git+https://github.com/StackExchange/apca-check.git" 17 | }, 18 | "license": "MIT", 19 | "files": [ 20 | "dist" 21 | ], 22 | "keywords": [ 23 | "accessibility", 24 | "a11y", 25 | "axe", 26 | "axe-core", 27 | "apca" 28 | ], 29 | "scripts": { 30 | "build": "tsc", 31 | "lint": "eslint ./src", 32 | "lint:fix": "eslint ./src --fix", 33 | "test": "web-test-runner", 34 | "test:watch": "web-test-runner --watch", 35 | "release": "npm run build && changeset publish" 36 | }, 37 | "dependencies": { 38 | "apca-w3": "^0.1.9" 39 | }, 40 | "peerDependencies": { 41 | "axe-core": "^4.0.0" 42 | }, 43 | "devDependencies": { 44 | "@changesets/changelog-github": "^0.5.0", 45 | "@changesets/cli": "^2.27.10", 46 | "@open-wc/testing": "^4.0.0", 47 | "@rollup/plugin-commonjs": "^26.0.1", 48 | "@types/apca-w3": "^0.1.3", 49 | "@typescript-eslint/eslint-plugin": "^7.18.0", 50 | "@typescript-eslint/parser": "^7.18.0", 51 | "@web/dev-server-esbuild": "^1.0.3", 52 | "@web/dev-server-rollup": "^0.6.4", 53 | "@web/test-runner": "^0.19.0", 54 | "@web/test-runner-playwright": "^0.11.0", 55 | "eslint": "^8.57.1", 56 | "eslint-config-prettier": "^9.1.0", 57 | "eslint-plugin-prettier": "^5.2.1", 58 | "prettier": "^3.3.3", 59 | "typescript": "^5.5.4" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/apca-bronze.ts: -------------------------------------------------------------------------------- 1 | import type { ConformanceThresholdFn } from "./index.js"; 2 | 3 | // APCA Bronze Level Conformance 4 | // https://readtech.org/ARC/tests/visual-readability-contrast/?tn=criterion 5 | 6 | const APCABronzeConformanceThresholdFn: ConformanceThresholdFn = (fontSize) => { 7 | const size = parseFloat(fontSize); 8 | switch (true) { 9 | case size >= 32: 10 | return 45; 11 | case size >= 16: 12 | return 60; 13 | default: 14 | return 75; 15 | } 16 | }; 17 | 18 | export default APCABronzeConformanceThresholdFn; 19 | -------------------------------------------------------------------------------- /src/apca-silver-plus.ts: -------------------------------------------------------------------------------- 1 | import type { ConformanceThresholdFn } from "./index.js"; 2 | 3 | const silverPlusAPCALookupTable = [ 4 | // See https://readtech.org/ARC/tests/visual-readability-contrast/?tn=criterion (May 22, 2022) 5 | // font size in px | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 weights 6 | [10, -1, -1, -1, -1, -1, -1, -1, -1, -1], 7 | [12, -1, -1, -1, -1, -1, -1, -1, -1, -1], 8 | [14, -1, -1, -1, 100, 100, 90, 75, -1, -1], 9 | [15, -1, -1, -1, 100, 100, 90, 70, -1, -1], 10 | [16, -1, -1, -1, 90, 75, 70, 60, 60, -1], 11 | [18, -1, -1, 100, 75, 70, 60, 55, 55, 55], 12 | [21, -1, -1, 90, 70, 60, 55, 50, 50, 50], 13 | [24, -1, -1, 75, 60, 55, 50, 45, 45, 45], 14 | [28, -1, 100, 70, 55, 50, 45, 43, 43, 43], 15 | [32, -1, 90, 65, 50, 45, 43, 40, 40, 40], 16 | [36, -1, 75, 60, 45, 43, 40, 38, 38, 38], 17 | [48, 90, 60, 55, 43, 40, 38, 35, 35, 35], 18 | [60, 75, 55, 50, 40, 38, 35, 33, 33, 33], 19 | [72, 60, 50, 45, 38, 35, 33, 30, 30, 30], 20 | [96, 50, 45, 40, 35, 33, 30, 25, 25, 25], 21 | ]; 22 | 23 | const APCASilverPlusConformanceThresholdFn: ConformanceThresholdFn = ( 24 | fontSize, 25 | fontWeight, 26 | ) => { 27 | const size = parseFloat(fontSize); 28 | const weight = parseFloat(fontWeight); 29 | 30 | // Go over the table backwards to find the first matching font size and then the weight. 31 | // The value null is returned when the combination of font size and weight does not have 32 | // any elegible APCA luminosity silver compliant thresholds (represented by -1 in the table). 33 | const reversedTable = [...silverPlusAPCALookupTable].reverse(); 34 | 35 | for (const [rowSize, ...rowWeights] of reversedTable) { 36 | if (size >= rowSize) { 37 | for (const [idx, keywordWeight] of [ 38 | 900, 800, 700, 600, 500, 400, 300, 200, 100, 39 | ].entries()) { 40 | if (weight >= keywordWeight) { 41 | const threshold = rowWeights[rowWeights.length - 1 - idx]; 42 | return threshold === -1 ? null : threshold; 43 | } 44 | } 45 | } 46 | } 47 | 48 | return null; 49 | }; 50 | 51 | export default APCASilverPlusConformanceThresholdFn; 52 | -------------------------------------------------------------------------------- /src/index.test.ts: -------------------------------------------------------------------------------- 1 | import { html, fixture, expect } from "@open-wc/testing"; 2 | import axe from "axe-core"; 3 | import type { AxeResults } from "axe-core"; 4 | import registerAPCACheck from "."; 5 | 6 | const runAxe = async (el: HTMLElement): Promise => { 7 | return new Promise((resolve, reject) => { 8 | axe.run(el, (err, results) => { 9 | if (err) reject(err); 10 | resolve(results); 11 | }); 12 | }); 13 | }; 14 | 15 | describe("apca-check", () => { 16 | describe("custom conformance level", () => { 17 | beforeEach(() => { 18 | const customConformanceThresholdFn = ( 19 | fontSize: string, 20 | ): number | null => { 21 | return parseFloat(fontSize) >= 32 ? 45 : 60; 22 | }; 23 | 24 | registerAPCACheck("custom", customConformanceThresholdFn); 25 | }); 26 | 27 | it("should throw an error if no custom conformance threshold function is provided", () => { 28 | expect(() => { 29 | registerAPCACheck("custom"); 30 | }).to.throw( 31 | "A custom conformance level requires a custom conformance threshold function", 32 | ); 33 | }); 34 | 35 | it("should check for APCA accessibility contrast violations", async () => { 36 | const el: HTMLElement = await fixture( 37 | html`

40 | Some copy 41 |

`, 42 | ); 43 | 44 | const results = await runAxe(el); 45 | 46 | const apcaPasses = results.passes.filter((violation) => 47 | violation.id.includes("color-contrast-apca-custom"), 48 | ); 49 | 50 | await expect(apcaPasses.length).to.equal(1); 51 | 52 | const passNode = apcaPasses[0].nodes[0]; 53 | expect(passNode.all[0].message).to.include( 54 | "Element has sufficient APCA custom level lightness contrast", 55 | ); 56 | }); 57 | 58 | it("should detect APCA accessibility contrast violations", async () => { 59 | const el: HTMLElement = await fixture( 60 | html`

63 | Some copy 64 |

`, 65 | ); 66 | 67 | const results = await runAxe(el); 68 | 69 | const apcaViolations = results.violations.filter((violation) => 70 | violation.id.includes("color-contrast-apca-custom"), 71 | ); 72 | 73 | await expect(apcaViolations.length).to.equal(1); 74 | 75 | const violationNode = apcaViolations[0].nodes[0]; 76 | expect(violationNode.failureSummary).to.include( 77 | "Element has insufficient APCA custom level contrast", 78 | ); 79 | }); 80 | 81 | it("should check nested nodes", async () => { 82 | const el: HTMLElement = await fixture( 83 | html`
84 |

Some title

85 |

Some copy

86 | 87 |
`, 88 | ); 89 | 90 | const results = await runAxe(el); 91 | 92 | const apcaViolations = results.violations.filter((violation) => 93 | violation.id.includes("color-contrast-apca-custom"), 94 | ); 95 | 96 | await expect(apcaViolations[0].nodes.length).to.equal(3); 97 | }); 98 | }); 99 | 100 | describe("bronze conformance level", () => { 101 | beforeEach(() => { 102 | registerAPCACheck("bronze"); 103 | }); 104 | 105 | it("should check for APCA accessibility contrast violations", async () => { 106 | const el: HTMLElement = await fixture( 107 | html`

110 | Some copy 111 |

`, 112 | ); 113 | 114 | const results = await runAxe(el); 115 | 116 | const apcaPasses = results.passes.filter((violation) => 117 | violation.id.includes("color-contrast-apca-bronze"), 118 | ); 119 | 120 | await expect(apcaPasses.length).to.equal(1); 121 | 122 | const passNode = apcaPasses[0].nodes[0]; 123 | expect(passNode.all[0].message).to.include( 124 | "Element has sufficient APCA bronze level lightness contrast", 125 | ); 126 | }); 127 | 128 | it("should detect APCA accessibility contrast violations", async () => { 129 | const el: HTMLElement = await fixture( 130 | html`

133 | Some copy 134 |

`, 135 | ); 136 | 137 | const results = await runAxe(el); 138 | 139 | const apcaViolations = results.violations.filter((violation) => 140 | violation.id.includes("color-contrast-apca-bronze"), 141 | ); 142 | 143 | await expect(apcaViolations.length).to.equal(1); 144 | 145 | const violationNode = apcaViolations[0].nodes[0]; 146 | expect(violationNode.failureSummary).to.include( 147 | "Element has insufficient APCA bronze level contrast", 148 | ); 149 | }); 150 | 151 | it("should check nested nodes", async () => { 152 | const el: HTMLElement = await fixture( 153 | html`
154 |

Some title

155 |

Some copy

156 | 157 |
`, 158 | ); 159 | 160 | const results = await runAxe(el); 161 | 162 | const apcaViolations = results.violations.filter((violation) => 163 | violation.id.includes("color-contrast-apca-bronze"), 164 | ); 165 | 166 | await expect(apcaViolations[0].nodes.length).to.equal(3); 167 | }); 168 | }); 169 | 170 | describe("silver conformance level", () => { 171 | beforeEach(() => { 172 | registerAPCACheck("silver"); 173 | }); 174 | 175 | it("should check for APCA accessibility contrast violations", async () => { 176 | const el: HTMLElement = await fixture( 177 | html`

180 | Some copy 181 |

`, 182 | ); 183 | 184 | const results = await runAxe(el); 185 | 186 | const apcaPasses = results.passes.filter((violation) => 187 | violation.id.includes("color-contrast-apca-silver"), 188 | ); 189 | 190 | await expect(apcaPasses.length).to.equal(1); 191 | 192 | const passNode = apcaPasses[0].nodes[0]; 193 | expect(passNode.all[0].message).to.include( 194 | "Element has sufficient APCA silver level lightness contrast", 195 | ); 196 | }); 197 | 198 | it("should detect APCA accessibility contrast violations", async () => { 199 | const el: HTMLElement = await fixture( 200 | html`

203 | Some copy 204 |

`, 205 | ); 206 | 207 | const results = await runAxe(el); 208 | 209 | const apcaViolations = results.violations.filter((violation) => 210 | violation.id.includes("color-contrast-apca-silver"), 211 | ); 212 | 213 | await expect(apcaViolations.length).to.equal(1); 214 | 215 | const violationNode = apcaViolations[0].nodes[0]; 216 | expect(violationNode.failureSummary).to.include( 217 | "Element has insufficient APCA silver level contrast", 218 | ); 219 | }); 220 | 221 | it("should check nested nodes", async () => { 222 | const el: HTMLElement = await fixture( 223 | html`
224 |

Some title

225 |

Some copy

226 | 227 |
`, 228 | ); 229 | 230 | const results = await runAxe(el); 231 | 232 | const apcaViolations = results.violations.filter((violation) => 233 | violation.id.includes("color-contrast-apca-silver"), 234 | ); 235 | 236 | await expect(apcaViolations[0].nodes.length).to.equal(3); 237 | }); 238 | 239 | it("should handle both valid code and violations", async () => { 240 | const el: HTMLElement = await fixture( 241 | html`
242 |

Some copy

243 |

Some copy

244 |
`, 245 | ); 246 | 247 | const results = await runAxe(el); 248 | 249 | const apcaViolations = results.violations.filter((violation) => 250 | violation.id.includes("color-contrast-apca-silver"), 251 | ); 252 | 253 | await expect(apcaViolations[0].nodes.length).to.equal(1); 254 | }); 255 | }); 256 | }); 257 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { calcAPCA } from "apca-w3"; 2 | import axe, { type Check, Rule } from "axe-core"; 3 | import APCABronzeConformanceThresholdFn from "./apca-bronze.js"; 4 | import APCASilverPlusConformanceThresholdFn from "./apca-silver-plus.js"; 5 | 6 | type ConformanceLevel = "bronze" | "silver" | "custom"; 7 | 8 | type ConformanceThresholdFn = ( 9 | fontSize: string, 10 | fontWeight: string, 11 | ) => number | null; 12 | 13 | // Augment Axe types to include the color utilities we use in this file 14 | // https://github.com/dequelabs/axe-core/blob/develop/lib/commons/color/color.js 15 | type Color = { 16 | red: number; 17 | green: number; 18 | blue: number; 19 | alpha: number; 20 | toHexString: () => string; 21 | }; 22 | declare module "axe-core" { 23 | interface Commons { 24 | color: { 25 | getForegroundColor: ( 26 | node: HTMLElement, 27 | _: unknown, 28 | bgColor: Color | null, 29 | ) => Color | null; 30 | getBackgroundColor: (node: HTMLElement) => Color | null; 31 | }; 32 | } 33 | } 34 | 35 | const generateColorContrastAPCAConformanceCheck = ( 36 | conformanceLevel: string, 37 | conformanceThresholdFn: ConformanceThresholdFn, 38 | ): Check => ({ 39 | id: `color-contrast-apca-${conformanceLevel}-conformance`, 40 | metadata: { 41 | impact: "serious", 42 | messages: { 43 | pass: 44 | "Element has sufficient APCA " + 45 | conformanceLevel + 46 | " level lightness contrast (Lc) of ${data.apcaContrast}Lc (foreground color: ${data.fgColor}, background color: ${data.bgColor}, font size: ${data.fontSize}, font weight: ${data.fontWeight}). Expected minimum APCA contrast of ${data.apcaThreshold}}", 47 | fail: { 48 | default: 49 | "Element has insufficient APCA " + 50 | conformanceLevel + 51 | " level contrast of ${data.apcaContrast}Lc (foreground color: ${data.fgColor}, background color: ${data.bgColor}, font size: ${data.fontSize}, font weight: ${data.fontWeight}). Expected minimum APCA lightness contrast of ${data.apcaThreshold}Lc", 52 | increaseFont: 53 | "Element has insufficient APCA " + 54 | conformanceLevel + 55 | " level contrast of ${data.apcaContrast}Lc (foreground color: ${data.fgColor}, background color: ${data.bgColor}, font size: ${data.fontSize}, font weight: ${data.fontWeight}). Increase font size and/or font weight to meet APCA conformance minimums", 56 | }, 57 | incomplete: "Unable to determine APCA lightness contrast (Lc)", 58 | }, 59 | }, 60 | evaluate(n) { 61 | const node = n as HTMLElement; 62 | const nodeStyle = window.getComputedStyle(node); 63 | const fontSize = nodeStyle.getPropertyValue("font-size"); 64 | const fontWeight = nodeStyle.getPropertyValue("font-weight"); 65 | 66 | const bgColor: Color | null = 67 | axe.commons.color.getBackgroundColor(node); 68 | const fgColor: Color | null = axe.commons.color.getForegroundColor( 69 | node, 70 | false, 71 | bgColor, 72 | ); 73 | 74 | // missing data to determine APCA contrast for this node 75 | if (!bgColor || !fgColor || !fontSize || !fontWeight) { 76 | return undefined; 77 | } 78 | 79 | const toRGBA = (color: Color) => { 80 | return `rgba(${color.red}, ${color.green}, ${color.blue}, ${color.alpha})`; 81 | }; 82 | 83 | const apcaContrast = Math.abs( 84 | calcAPCA(toRGBA(fgColor), toRGBA(bgColor)) as number, 85 | ); 86 | const apcaThreshold = conformanceThresholdFn(fontSize, fontWeight); 87 | 88 | this.data({ 89 | fgColor: fgColor.toHexString(), 90 | bgColor: bgColor.toHexString(), 91 | fontSize: `${((parseFloat(fontSize) * 72) / 96).toFixed( 92 | 1, 93 | )}pt (${parseFloat(fontSize)}px)`, 94 | fontWeight: fontWeight, 95 | apcaContrast: Math.round(apcaContrast * 100) / 100, 96 | apcaThreshold: apcaThreshold, 97 | messageKey: apcaThreshold === null ? "increaseFont" : "default", 98 | }); 99 | 100 | return apcaThreshold ? apcaContrast >= apcaThreshold : false; 101 | }, 102 | }); 103 | 104 | const generateColorContrastAPCARule = (conformanceLevel: string): Rule => ({ 105 | id: `color-contrast-apca-${conformanceLevel}`, 106 | impact: "serious", 107 | matches: "color-contrast-matches", 108 | metadata: { 109 | description: `Ensures the contrast between foreground and background colors meets APCA ${conformanceLevel} level conformance minimums thresholds`, 110 | help: "Elements must meet APCA conformance minimums thresholds", 111 | helpUrl: 112 | "https://readtech.org/ARC/tests/visual-readability-contrast/?tn=criterion", 113 | }, 114 | all: [`color-contrast-apca-${conformanceLevel}-conformance`], 115 | tags: ["apca", "wcag3", `apca-${conformanceLevel}`], 116 | }); 117 | 118 | const registerAPCACheck = ( 119 | conformanceLevel: ConformanceLevel, 120 | customConformanceThresholdFn?: ConformanceThresholdFn, 121 | ) => { 122 | if ( 123 | conformanceLevel === "custom" && 124 | typeof customConformanceThresholdFn !== "function" 125 | ) { 126 | throw new Error( 127 | "A custom conformance level requires a custom conformance threshold function", 128 | ); 129 | } 130 | 131 | const conformanceThresholdFnMap = { 132 | bronze: APCABronzeConformanceThresholdFn, 133 | silver: APCASilverPlusConformanceThresholdFn, 134 | custom: customConformanceThresholdFn!, 135 | }; 136 | 137 | axe.configure({ 138 | rules: [generateColorContrastAPCARule(conformanceLevel)], 139 | checks: [ 140 | generateColorContrastAPCAConformanceCheck( 141 | conformanceLevel, 142 | conformanceThresholdFnMap[conformanceLevel], 143 | ), 144 | ], 145 | }); 146 | }; 147 | 148 | export type { ConformanceLevel, ConformanceThresholdFn }; 149 | export default registerAPCACheck; 150 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "target": "esnext", 5 | "module": "nodenext", 6 | "declaration": true, 7 | "outDir": "./dist", 8 | }, 9 | "include": ["src/**/*"], 10 | "exclude": ["**/*.test.ts"] 11 | } -------------------------------------------------------------------------------- /web-test-runner.config.mjs: -------------------------------------------------------------------------------- 1 | import { fromRollup } from "@web/dev-server-rollup"; 2 | import { esbuildPlugin } from "@web/dev-server-esbuild"; 3 | import _commonjs from "@rollup/plugin-commonjs"; 4 | import { playwrightLauncher } from "@web/test-runner-playwright"; 5 | 6 | const commonjs = fromRollup(_commonjs); 7 | 8 | export default { 9 | files: "src/**/*.test.ts", 10 | browsers: [ 11 | playwrightLauncher({ product: "chromium" }), 12 | playwrightLauncher({ product: "firefox" }), 13 | playwrightLauncher({ product: "webkit" }), 14 | ], 15 | nodeResolve: { browser: true }, 16 | plugins: [commonjs(), esbuildPlugin({ ts: true })], 17 | }; 18 | --------------------------------------------------------------------------------