Skip to content

Main content

WCAG Contrast Checker Source Code

Browse the implementation files for WCAG Contrast Checker.
tool.ts typescript
import WcagContrastCheck from './WcagContrastCheck.svelte';
import { calculateWcagContrast } from './calculation';

export const wcagContrastCheck = (
	foreground: unknown = '#777777',
	background: unknown = '#FFFFFF'
): string => {
	const result = calculateWcagContrast(foreground, background);
	return result ? JSON.stringify(result) : '';
};

export const wcagContrastPreview = (
	foreground: unknown = '#777777',
	background: unknown = '#FFFFFF'
): string => {
	const result = calculateWcagContrast(foreground, background);
	if (!result) return '';
	const status = (passes: boolean, enhanced = false) =>
		passes ? (enhanced ? '✓✓' : '✓') : '✕';

	return `${result.ratio}:1\n\n${status(
		result.passes.aaNormal
	)} AA normal\n${status(
		result.passes.aaLarge
	)} AA large\n${status(
		result.passes.aaaNormal,
		true
	)} AAA normal\n${status(
		result.passes.aaaLarge,
		true
	)} AAA large`;
};

export const Tool: TypeTool = {
	name: 'WCAG Contrast Checker',
	slug: 'wcag-contrast-check',
	intro:
		'Check the contrast between text and background colors against WCAG AA and AAA thresholds.',
	tool: wcagContrastCheck,
	i: [
		{
			example: '#777777',
			label: 'Foreground color',
			placeholder: '#RRGGBB or rgb(r, g, b)',
			type: 'color',
			value: '#777777'
		},
		{
			example: '#FFFFFF',
			label: 'Background color',
			placeholder: '#RRGGBB or rgb(r, g, b)',
			type: 'color',
			value: '#FFFFFF'
		}
	],
	o: [
		{
			label: 'WCAG contrast result',
			placeholder: 'WCAG contrast result',
			render: 'custom',
			renderas: WcagContrastCheck,
			type: 'text'
		}
	],
	preview: {
		i: [
			{
				label: 'Foreground',
				placeholder: '#777777',
				type: 'color',
				value: '#777777'
			},
			{
				label: 'Background',
				placeholder: '#FFFFFF',
				type: 'color',
				value: '#FFFFFF'
			}
		],
		o: [
			{
				label: 'Contrast',
				placeholder: 'WCAG contrast result',
				render: 'textarea',
				type: 'text'
			}
		],
		tool: wcagContrastPreview
	},
	alternative: [
		{ title: 'WCAG 2.2 Reference', url: '/reference/wcag' },
		{ title: 'HEX to RGB Converter', url: '/hex-to-rgb' },
		{ title: 'UI / UX Cheatsheet', url: '/cheatsheet/ui-ux' }
	],
	cite: [
		{
			title: 'WCAG 2.1: Contrast (Minimum)',
			url: 'https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum'
		},
		{
			title: 'WCAG 2.1: Contrast (Enhanced)',
			url: 'https://www.w3.org/WAI/WCAG21/Understanding/contrast-enhanced'
		}
	]
};

export default Tool;

Description

Browse the implementation files for WCAG Contrast Checker.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools