@opendata-ai/openchart-core 8.0.0-rc.9 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.ts +403 -45
  3. package/dist/index.js +50 -18
  4. package/dist/index.js.map +1 -1
  5. package/dist/styles.css +1 -1
  6. package/dist/styles.css.map +1 -1
  7. package/package.json +1 -2
  8. package/schema/chart.schema.json +375 -69
  9. package/schema/table.schema.json +35 -1
  10. package/schema/vizspec.schema.json +992 -171
  11. package/src/accessibility/__tests__/alt-text.test.ts +0 -110
  12. package/src/accessibility/__tests__/aria.test.ts +0 -125
  13. package/src/accessibility/alt-text.ts +0 -155
  14. package/src/accessibility/aria.ts +0 -75
  15. package/src/accessibility/index.ts +0 -6
  16. package/src/colors/__tests__/colorblind.test.ts +0 -75
  17. package/src/colors/__tests__/contrast.test.ts +0 -119
  18. package/src/colors/__tests__/palettes.test.ts +0 -74
  19. package/src/colors/colorblind.ts +0 -131
  20. package/src/colors/contrast.ts +0 -143
  21. package/src/colors/index.ts +0 -36
  22. package/src/colors/palettes.ts +0 -206
  23. package/src/helpers/__tests__/deep-merge.test.ts +0 -54
  24. package/src/helpers/__tests__/spec-builders.test.ts +0 -338
  25. package/src/helpers/deep-merge.ts +0 -29
  26. package/src/helpers/spec-builders.ts +0 -479
  27. package/src/index.ts +0 -215
  28. package/src/labels/__tests__/collision.test.ts +0 -310
  29. package/src/labels/collision.ts +0 -249
  30. package/src/labels/index.ts +0 -13
  31. package/src/layout/__tests__/chrome.test.ts +0 -208
  32. package/src/layout/__tests__/text-measure.test.ts +0 -57
  33. package/src/layout/chrome.ts +0 -470
  34. package/src/layout/index.ts +0 -18
  35. package/src/layout/text-measure.ts +0 -404
  36. package/src/layout/text-wrap.ts +0 -93
  37. package/src/locale/__tests__/format.test.ts +0 -606
  38. package/src/locale/format.ts +0 -459
  39. package/src/locale/index.ts +0 -21
  40. package/src/responsive/__tests__/breakpoints.test.ts +0 -146
  41. package/src/responsive/__tests__/metrics.test.ts +0 -52
  42. package/src/responsive/breakpoints.ts +0 -177
  43. package/src/responsive/index.ts +0 -53
  44. package/src/responsive/metrics.ts +0 -299
  45. package/src/schema/__tests__/generated-artifacts.test.ts +0 -42
  46. package/src/schema/__tests__/schema.test.ts +0 -179
  47. package/src/styles/__tests__/reduced-motion-selectors.test.ts +0 -28
  48. package/src/styles/animation.css +0 -213
  49. package/src/styles/base.css +0 -102
  50. package/src/styles/chrome.css +0 -174
  51. package/src/styles/dark.css +0 -44
  52. package/src/styles/graph.css +0 -135
  53. package/src/styles/index.css +0 -28
  54. package/src/styles/keyframes.css +0 -151
  55. package/src/styles/legend.css +0 -18
  56. package/src/styles/reduced-motion.css +0 -67
  57. package/src/styles/series-search.css +0 -153
  58. package/src/styles/sparkline.css +0 -16
  59. package/src/styles/table-animation.css +0 -93
  60. package/src/styles/table.css +0 -398
  61. package/src/styles/token-definitions.ts +0 -199
  62. package/src/styles/tokens.css +0 -156
  63. package/src/styles/tooltip.css +0 -126
  64. package/src/styles/you-draw-it.css +0 -126
  65. package/src/theme/__tests__/dark-mode.test.ts +0 -232
  66. package/src/theme/__tests__/defaults.test.ts +0 -73
  67. package/src/theme/__tests__/resolve.test.ts +0 -277
  68. package/src/theme/dark-mode.ts +0 -258
  69. package/src/theme/defaults.ts +0 -110
  70. package/src/theme/index.ts +0 -8
  71. package/src/theme/presets.ts +0 -64
  72. package/src/theme/resolve.ts +0 -312
  73. package/src/types/__tests__/encoding.test.ts +0 -368
  74. package/src/types/__tests__/gradient.test.ts +0 -95
  75. package/src/types/__tests__/spec.test.ts +0 -499
  76. package/src/types/encoding.ts +0 -280
  77. package/src/types/events.ts +0 -236
  78. package/src/types/index.ts +0 -290
  79. package/src/types/layout.ts +0 -2024
  80. package/src/types/schema-roots.ts +0 -32
  81. package/src/types/spec.ts +0 -2925
  82. package/src/types/table.ts +0 -108
  83. package/src/types/theme.ts +0 -209
@@ -1,110 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import type { ChartSpec } from '../../types/spec';
3
- import { generateAltText, generateDataTable } from '../alt-text';
4
-
5
- const lineSpec: ChartSpec = {
6
- mark: 'line',
7
- data: [
8
- { date: '2020-01-01', value: 10, country: 'US' },
9
- { date: '2021-01-01', value: 20, country: 'US' },
10
- { date: '2020-01-01', value: 15, country: 'UK' },
11
- { date: '2021-01-01', value: 25, country: 'UK' },
12
- ],
13
- encoding: {
14
- x: { field: 'date', type: 'temporal' },
15
- y: { field: 'value', type: 'quantitative' },
16
- color: { field: 'country', type: 'nominal' },
17
- },
18
- chrome: { title: 'GDP Growth Rate' },
19
- };
20
-
21
- const barSpec: ChartSpec = {
22
- mark: 'bar',
23
- data: [
24
- { category: 'A', value: 10 },
25
- { category: 'B', value: 20 },
26
- { category: 'C', value: 30 },
27
- ],
28
- encoding: {
29
- x: { field: 'category', type: 'nominal' },
30
- y: { field: 'value', type: 'quantitative' },
31
- },
32
- };
33
-
34
- describe('generateAltText', () => {
35
- it('includes chart type', () => {
36
- const alt = generateAltText(lineSpec, lineSpec.data);
37
- expect(alt).toContain('Line chart');
38
- });
39
-
40
- it('includes title when present', () => {
41
- const alt = generateAltText(lineSpec, lineSpec.data);
42
- expect(alt).toContain('GDP Growth Rate');
43
- });
44
-
45
- it('includes temporal range', () => {
46
- const alt = generateAltText(lineSpec, lineSpec.data);
47
- expect(alt).toContain('from 2020 to 2021');
48
- });
49
-
50
- it('includes series count and names', () => {
51
- const alt = generateAltText(lineSpec, lineSpec.data);
52
- expect(alt).toContain('2 series');
53
- expect(alt).toContain('US');
54
- expect(alt).toContain('UK');
55
- });
56
-
57
- it('includes data point count', () => {
58
- const alt = generateAltText(lineSpec, lineSpec.data);
59
- expect(alt).toContain('4 data points');
60
- });
61
-
62
- it('handles categorical x-axis', () => {
63
- const alt = generateAltText(barSpec, barSpec.data);
64
- expect(alt).toContain('Bar chart');
65
- expect(alt).toContain('3 categories');
66
- });
67
-
68
- it('handles missing chrome gracefully', () => {
69
- const alt = generateAltText(barSpec, barSpec.data);
70
- expect(alt).toBeTruthy();
71
- expect(alt).not.toContain('showing undefined');
72
- });
73
- });
74
-
75
- describe('generateDataTable', () => {
76
- it('includes headers as first row', () => {
77
- const table = generateDataTable(lineSpec, lineSpec.data);
78
- expect(table[0]).toEqual(['date', 'value', 'country']);
79
- });
80
-
81
- it('includes data rows', () => {
82
- const table = generateDataTable(lineSpec, lineSpec.data);
83
- expect(table).toHaveLength(5); // 1 header + 4 data rows
84
- expect(table[1]).toEqual(['2020-01-01', 10, 'US']);
85
- });
86
-
87
- it('only includes encoded fields', () => {
88
- const spec: ChartSpec = {
89
- mark: 'bar',
90
- data: [{ category: 'A', value: 10, extra: 'ignored' }],
91
- encoding: {
92
- x: { field: 'category', type: 'nominal' },
93
- y: { field: 'value', type: 'quantitative' },
94
- },
95
- };
96
- const table = generateDataTable(spec, spec.data);
97
- expect(table[0]).toEqual(['category', 'value']);
98
- expect(table[1]).toEqual(['A', 10]);
99
- });
100
-
101
- it('returns empty for spec with no encoding fields', () => {
102
- const spec: ChartSpec = {
103
- mark: 'arc',
104
- data: [{ value: 10 }],
105
- encoding: {},
106
- };
107
- const table = generateDataTable(spec, spec.data);
108
- expect(table).toEqual([]);
109
- });
110
- });
@@ -1,125 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import type { Mark, MarkAria } from '../../types/layout';
3
- import { generateAriaLabels } from '../aria';
4
-
5
- const defaultAria: MarkAria = { label: 'test' };
6
-
7
- describe('generateAriaLabels', () => {
8
- it('generates labels for line marks', () => {
9
- const marks: Mark[] = [
10
- {
11
- type: 'line',
12
- points: [
13
- { x: 0, y: 0 },
14
- { x: 10, y: 10 },
15
- ],
16
- stroke: '#333',
17
- strokeWidth: 2,
18
- seriesKey: 'US',
19
- data: [],
20
- aria: defaultAria,
21
- },
22
- ];
23
-
24
- const labels = generateAriaLabels(marks);
25
- expect(labels.get('mark-0')).toContain('Line series: US');
26
- expect(labels.get('mark-0')).toContain('2 points');
27
- });
28
-
29
- it('generates labels for rect marks', () => {
30
- const marks: Mark[] = [
31
- {
32
- type: 'rect',
33
- x: 0,
34
- y: 0,
35
- width: 50,
36
- height: 100,
37
- fill: '#1b7fa3',
38
- data: { category: 'Tech', value: 42 },
39
- aria: defaultAria,
40
- },
41
- ];
42
-
43
- const labels = generateAriaLabels(marks);
44
- expect(labels.get('mark-0')).toContain('Data point');
45
- expect(labels.get('mark-0')).toContain('category: Tech');
46
- expect(labels.get('mark-0')).toContain('value: 42');
47
- });
48
-
49
- it('generates labels for arc marks', () => {
50
- const marks: Mark[] = [
51
- {
52
- type: 'arc',
53
- path: 'M...',
54
- centroid: { x: 50, y: 50 },
55
- innerRadius: 0,
56
- outerRadius: 100,
57
- startAngle: 0,
58
- endAngle: Math.PI,
59
- fill: '#e15759',
60
- stroke: '#fff',
61
- strokeWidth: 1,
62
- data: { sector: 'Healthcare', percent: 25 },
63
- aria: defaultAria,
64
- },
65
- ];
66
-
67
- const labels = generateAriaLabels(marks);
68
- expect(labels.get('mark-0')).toContain('Slice');
69
- expect(labels.get('mark-0')).toContain('Healthcare');
70
- });
71
-
72
- it('generates labels for point marks', () => {
73
- const marks: Mark[] = [
74
- {
75
- type: 'point',
76
- cx: 100,
77
- cy: 200,
78
- r: 5,
79
- fill: '#333',
80
- stroke: '#333',
81
- strokeWidth: 1,
82
- data: { x: 10, y: 20 },
83
- aria: defaultAria,
84
- },
85
- ];
86
-
87
- const labels = generateAriaLabels(marks);
88
- expect(labels.get('mark-0')).toContain('Data point');
89
- expect(labels.get('mark-0')).toContain('x: 10');
90
- });
91
-
92
- it('handles empty marks array', () => {
93
- const labels = generateAriaLabels([]);
94
- expect(labels.size).toBe(0);
95
- });
96
-
97
- it('handles multiple marks with sequential keys', () => {
98
- const marks: Mark[] = [
99
- {
100
- type: 'rect',
101
- x: 0,
102
- y: 0,
103
- width: 10,
104
- height: 10,
105
- fill: '#333',
106
- data: { a: 1 },
107
- aria: defaultAria,
108
- },
109
- {
110
- type: 'rect',
111
- x: 20,
112
- y: 0,
113
- width: 10,
114
- height: 10,
115
- fill: '#666',
116
- data: { a: 2 },
117
- aria: defaultAria,
118
- },
119
- ];
120
-
121
- const labels = generateAriaLabels(marks);
122
- expect(labels.has('mark-0')).toBe(true);
123
- expect(labels.has('mark-1')).toBe(true);
124
- });
125
- });
@@ -1,155 +0,0 @@
1
- /**
2
- * Automatic alt text generation for chart accessibility.
3
- *
4
- * Produces human-readable descriptions of chart content for screen readers
5
- * and a tabular fallback for data access.
6
- */
7
-
8
- import type { ChartSpec, DataRow } from '../types/spec';
9
- import { MARK_DISPLAY_NAMES, resolveMarkDef, resolveMarkType } from '../types/spec';
10
-
11
- // ---------------------------------------------------------------------------
12
- // Alt text generation
13
- // ---------------------------------------------------------------------------
14
-
15
- /**
16
- * Generate alt text describing a chart's content.
17
- *
18
- * Produces a description like:
19
- * "Line chart showing GDP Growth Rate from 2020 to 2024 with 2 series (US, UK)"
20
- *
21
- * @param spec - The chart spec.
22
- * @param data - The data array.
23
- */
24
- export function generateAltText(spec: ChartSpec, data: DataRow[]): string {
25
- const markType = resolveMarkType(spec.mark);
26
- const markDef = resolveMarkDef(spec.mark);
27
- let chartName = MARK_DISPLAY_NAMES[markType] ?? `${markType} chart`;
28
-
29
- // Special case: donut detection
30
- if (markType === 'arc' && markDef.innerRadius && markDef.innerRadius > 0) {
31
- chartName = 'Donut chart';
32
- }
33
-
34
- const parts: string[] = [chartName];
35
-
36
- // Add title context if present
37
- const title = spec.chrome?.title;
38
- if (title) {
39
- const titleText = typeof title === 'string' ? title : title.text;
40
- parts.push(`showing ${titleText}`);
41
- }
42
-
43
- // Waffle: name the unit framing. Per-category "x of N units" phrasing
44
- // lives on the mark aria labels; the chart-level text carries the total.
45
- if (markType === 'waffle') {
46
- const units = markDef.units ?? 100;
47
- parts.push(`dividing ${units} units`);
48
- }
49
-
50
- // Parliament: name the total seat count and the majority threshold, the two
51
- // numbers a reader most wants. Per-party seat counts live on the seat marks'
52
- // aria labels; this carries the overall framing.
53
- if (markType === 'parliament') {
54
- const valueField = spec.encoding.theta?.field ?? spec.encoding.y?.field;
55
- if (valueField) {
56
- const totalSeats = data.reduce((sum, d) => {
57
- const v = Number(d[valueField]);
58
- return sum + (Number.isFinite(v) && v > 0 ? v : 0);
59
- }, 0);
60
- if (totalSeats > 0) {
61
- const majority = Math.floor(totalSeats / 2) + 1;
62
- parts.push(`with ${totalSeats} seats, ${majority} needed for a majority`);
63
- }
64
- }
65
- }
66
-
67
- // Beeswarm: name the distribution fields (value axis + optional lane).
68
- // Skips the generic x-axis description below, which would either say
69
- // nothing (quantitative value axis) or repeat the lane count.
70
- if (markType === 'beeswarm') {
71
- const xIsValue = spec.encoding.x?.type === 'quantitative';
72
- const valueField = xIsValue ? spec.encoding.x?.field : spec.encoding.y?.field;
73
- const laneField = xIsValue ? spec.encoding.y?.field : spec.encoding.x?.field;
74
- if (valueField) {
75
- parts.push(
76
- `plotting the distribution of ${valueField}${laneField ? ` by ${laneField}` : ''}`,
77
- );
78
- }
79
- }
80
-
81
- // Describe the data range
82
- if (spec.encoding.x && markType !== 'beeswarm' && data.length > 0) {
83
- const field = spec.encoding.x.field;
84
- const values = data.map((d) => d[field]).filter((v) => v != null);
85
-
86
- if (values.length > 0) {
87
- if (spec.encoding.x.type === 'temporal') {
88
- const dates = values.map((v) => (v instanceof Date ? v : new Date(String(v))));
89
- const validDates = dates.filter((d) => !Number.isNaN(d.getTime()));
90
- if (validDates.length >= 2) {
91
- validDates.sort((a, b) => a.getTime() - b.getTime());
92
- const first = validDates[0].getUTCFullYear();
93
- const last = validDates[validDates.length - 1].getUTCFullYear();
94
- if (first !== last) {
95
- parts.push(`from ${first} to ${last}`);
96
- }
97
- }
98
- } else if (spec.encoding.x.type === 'nominal' || spec.encoding.x.type === 'ordinal') {
99
- const uniqueValues = [...new Set(values.map(String))];
100
- parts.push(`across ${uniqueValues.length} categories`);
101
- }
102
- }
103
- }
104
-
105
- // Describe series if color encoding is present
106
- if (spec.encoding.color && 'field' in spec.encoding.color && data.length > 0) {
107
- const colorField = spec.encoding.color.field;
108
- const uniqueSeries = [...new Set(data.map((d) => String(d[colorField])).filter(Boolean))];
109
- if (uniqueSeries.length > 0) {
110
- parts.push(`with ${uniqueSeries.length} series (${uniqueSeries.join(', ')})`);
111
- }
112
- }
113
-
114
- // Add data point count
115
- parts.push(`(${data.length} data points)`);
116
-
117
- return parts.join(' ');
118
- }
119
-
120
- // ---------------------------------------------------------------------------
121
- // Data table fallback
122
- // ---------------------------------------------------------------------------
123
-
124
- /**
125
- * Generate a tabular data fallback for screen readers.
126
- *
127
- * Returns a 2D array where the first row is headers and subsequent
128
- * rows are data values. Only includes fields referenced in the encoding.
129
- *
130
- * @param spec - The chart spec.
131
- * @param data - The data array.
132
- */
133
- export function generateDataTable(spec: ChartSpec, data: DataRow[]): unknown[][] {
134
- // Collect fields from encoding
135
- const fields: string[] = [];
136
- const encoding = spec.encoding;
137
-
138
- if (encoding.x) fields.push(encoding.x.field);
139
- if (encoding.y) fields.push(encoding.y.field);
140
- if (encoding.color && 'field' in encoding.color) fields.push(encoding.color.field);
141
- if (encoding.size && 'field' in encoding.size) fields.push(encoding.size.field);
142
-
143
- // Deduplicate
144
- const uniqueFields = [...new Set(fields)];
145
-
146
- if (uniqueFields.length === 0) return [];
147
-
148
- // Header row
149
- const headers = uniqueFields;
150
-
151
- // Data rows
152
- const rows = data.map((row) => uniqueFields.map((field) => row[field] ?? ''));
153
-
154
- return [headers, ...rows];
155
- }
@@ -1,75 +0,0 @@
1
- /**
2
- * ARIA label generation for individual marks.
3
- *
4
- * Produces per-mark labels for screen reader navigation, enabling
5
- * users to explore data points individually.
6
- */
7
-
8
- import { defaultNumberFormatter } from '../locale/format';
9
- import type { Mark } from '../types/layout';
10
-
11
- /**
12
- * Generate ARIA labels for a set of marks.
13
- *
14
- * Returns a Map keyed by a mark identifier (index-based) with
15
- * descriptive labels like "Data point: US GDP 42 in 2020-01".
16
- *
17
- * @param marks - Array of mark objects from the compiled chart layout.
18
- */
19
- export function generateAriaLabels(marks: Mark[]): Map<string, string> {
20
- const labels = new Map<string, string>();
21
-
22
- for (let i = 0; i < marks.length; i++) {
23
- const mark = marks[i];
24
- const key = `mark-${i}`;
25
-
26
- switch (mark.type) {
27
- case 'line': {
28
- const series = mark.seriesKey ?? 'Series';
29
- const pointCount = mark.points.length;
30
- labels.set(key, `Line series: ${series} with ${pointCount} points`);
31
- break;
32
- }
33
-
34
- case 'area': {
35
- const series = mark.seriesKey ?? 'Area';
36
- labels.set(key, `Area series: ${series}`);
37
- break;
38
- }
39
-
40
- case 'rect': {
41
- const dataEntries = Object.entries(mark.data).filter(([k]) => !k.startsWith('_'));
42
- const description = dataEntries.map(([k, v]) => `${k}: ${formatValue(v)}`).join(', ');
43
- labels.set(key, `Data point: ${description}`);
44
- break;
45
- }
46
-
47
- case 'arc': {
48
- const dataEntries = Object.entries(mark.data).filter(([k]) => !k.startsWith('_'));
49
- const description = dataEntries.map(([k, v]) => `${k}: ${formatValue(v)}`).join(', ');
50
- labels.set(key, `Slice: ${description}`);
51
- break;
52
- }
53
-
54
- case 'point': {
55
- const dataEntries = Object.entries(mark.data).filter(([k]) => !k.startsWith('_'));
56
- const description = dataEntries.map(([k, v]) => `${k}: ${formatValue(v)}`).join(', ');
57
- labels.set(key, `Data point: ${description}`);
58
- break;
59
- }
60
- }
61
- }
62
-
63
- return labels;
64
- }
65
-
66
- const ariaNumberFormatter = defaultNumberFormatter();
67
-
68
- function formatValue(value: unknown): string {
69
- if (value == null) return 'N/A';
70
- if (value instanceof Date) return value.toISOString().slice(0, 10);
71
- if (typeof value === 'number') {
72
- return ariaNumberFormatter(value);
73
- }
74
- return String(value);
75
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * Accessibility module barrel export.
3
- */
4
-
5
- export { generateAltText, generateDataTable } from './alt-text';
6
- export { generateAriaLabels } from './aria';
@@ -1,75 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { checkPaletteDistinguishability, simulateColorBlindness } from '../colorblind';
3
-
4
- describe('simulateColorBlindness', () => {
5
- it('returns a valid hex color for protanopia', () => {
6
- const result = simulateColorBlindness('#e15759', 'protanopia');
7
- expect(result).toMatch(/^#[0-9a-f]{6}$/i);
8
- });
9
-
10
- it('returns a valid hex color for deuteranopia', () => {
11
- const result = simulateColorBlindness('#59a14f', 'deuteranopia');
12
- expect(result).toMatch(/^#[0-9a-f]{6}$/i);
13
- });
14
-
15
- it('returns a valid hex color for tritanopia', () => {
16
- const result = simulateColorBlindness('#1b7fa3', 'tritanopia');
17
- expect(result).toMatch(/^#[0-9a-f]{6}$/i);
18
- });
19
-
20
- it('pure grey remains close to grey under all types', () => {
21
- const grey = '#808080';
22
- for (const type of ['protanopia', 'deuteranopia', 'tritanopia'] as const) {
23
- const sim = simulateColorBlindness(grey, type);
24
- // Simulated grey should still be roughly grey (all channels similar)
25
- const match = sim.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
26
- expect(match).not.toBeNull();
27
- if (match) {
28
- const [r, g, b] = [parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16)];
29
- // All channels should be within ~40 of each other
30
- const max = Math.max(r, g, b);
31
- const min = Math.min(r, g, b);
32
- expect(max - min).toBeLessThan(40);
33
- }
34
- }
35
- });
36
-
37
- it('red and green become similar under protanopia', () => {
38
- const simRed = simulateColorBlindness('#ff0000', 'protanopia');
39
- const simGreen = simulateColorBlindness('#00ff00', 'protanopia');
40
- // They should be more similar than the originals
41
- // (we just verify they're both valid, the matrix math handles the rest)
42
- expect(simRed).toMatch(/^#[0-9a-f]{6}$/i);
43
- expect(simGreen).toMatch(/^#[0-9a-f]{6}$/i);
44
- });
45
-
46
- it('achromatopsia collapses every color to a grey', () => {
47
- for (const color of ['#e15759', '#59a14f', '#1b7fa3']) {
48
- const sim = simulateColorBlindness(color, 'achromatopsia');
49
- const match = sim.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
50
- expect(match).not.toBeNull();
51
- if (match) {
52
- const [r, g, b] = [parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16)];
53
- expect(Math.max(r, g, b) - Math.min(r, g, b)).toBeLessThanOrEqual(1);
54
- }
55
- }
56
- });
57
- });
58
-
59
- describe('checkPaletteDistinguishability', () => {
60
- it('returns true for very different colors', () => {
61
- expect(checkPaletteDistinguishability(['#ff0000', '#0000ff', '#ffffff'], 'protanopia')).toBe(
62
- true,
63
- );
64
- });
65
-
66
- it('returns false for near-identical colors', () => {
67
- expect(
68
- checkPaletteDistinguishability(['#ff0000', '#ff0200', '#ff0100'], 'protanopia', 30),
69
- ).toBe(false);
70
- });
71
-
72
- it('handles single-color palettes (vacuously true)', () => {
73
- expect(checkPaletteDistinguishability(['#ff0000'], 'deuteranopia')).toBe(true);
74
- });
75
- });
@@ -1,119 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { contrastRatio, findAccessibleColor, meetsAA, pickLabelColor } from '../contrast';
3
-
4
- describe('contrastRatio', () => {
5
- it('returns 21 for black on white', () => {
6
- const ratio = contrastRatio('#000000', '#ffffff');
7
- expect(ratio).toBeCloseTo(21, 0);
8
- });
9
-
10
- it('returns 1 for identical colors', () => {
11
- const ratio = contrastRatio('#336699', '#336699');
12
- expect(ratio).toBeCloseTo(1, 1);
13
- });
14
-
15
- it('is commutative (order does not matter)', () => {
16
- const a = contrastRatio('#1b7fa3', '#ffffff');
17
- const b = contrastRatio('#ffffff', '#1b7fa3');
18
- expect(a).toBeCloseTo(b, 5);
19
- });
20
-
21
- it('computes known contrast ratios within tolerance', () => {
22
- // White text on dark blue: should be high contrast
23
- const ratio = contrastRatio('#ffffff', '#003366');
24
- expect(ratio).toBeGreaterThan(8);
25
- });
26
- });
27
-
28
- describe('meetsAA', () => {
29
- it('black on white meets AA for normal text', () => {
30
- expect(meetsAA('#000000', '#ffffff')).toBe(true);
31
- });
32
-
33
- it('light grey on white fails AA for normal text', () => {
34
- expect(meetsAA('#cccccc', '#ffffff')).toBe(false);
35
- });
36
-
37
- it('uses 3:1 threshold for large text', () => {
38
- // Find a color that has ratio between 3 and 4.5
39
- // Medium grey on white has ~3.9:1 ratio
40
- const ratio = contrastRatio('#767676', '#ffffff');
41
- expect(ratio).toBeGreaterThanOrEqual(3);
42
- expect(ratio).toBeLessThan(5);
43
- // Should fail normal text but pass large text
44
- expect(meetsAA('#767676', '#ffffff', true)).toBe(true);
45
- });
46
- });
47
-
48
- describe('findAccessibleColor', () => {
49
- it('returns the original color if already accessible', () => {
50
- const result = findAccessibleColor('#000000', '#ffffff');
51
- expect(result).toBe('#000000');
52
- });
53
-
54
- it('darkens a light color to meet contrast on white', () => {
55
- const result = findAccessibleColor('#cccccc', '#ffffff');
56
- const ratio = contrastRatio(result, '#ffffff');
57
- expect(ratio).toBeGreaterThanOrEqual(4.5);
58
- });
59
-
60
- it('lightens a dark color to meet contrast on dark background', () => {
61
- const result = findAccessibleColor('#333333', '#09090b');
62
- const ratio = contrastRatio(result, '#09090b');
63
- expect(ratio).toBeGreaterThanOrEqual(4.5);
64
- });
65
-
66
- it('respects custom target ratio', () => {
67
- const result = findAccessibleColor('#aaaaaa', '#ffffff', 7);
68
- const ratio = contrastRatio(result, '#ffffff');
69
- expect(ratio).toBeGreaterThanOrEqual(7);
70
- });
71
- });
72
-
73
- describe('pickLabelColor', () => {
74
- it('returns white for dark backgrounds', () => {
75
- expect(pickLabelColor('#1a1a2e')).toBe('#ffffff');
76
- expect(pickLabelColor('#2563eb')).toBe('#ffffff');
77
- expect(pickLabelColor('#000000')).toBe('#ffffff');
78
- });
79
-
80
- it('returns dark for light backgrounds', () => {
81
- expect(pickLabelColor('#ffffff')).toBe('#111111');
82
- expect(pickLabelColor('#f0f0f0')).toBe('#111111');
83
- expect(pickLabelColor('#e2e8f0')).toBe('#111111');
84
- });
85
-
86
- it('returns white for saturated mid-tone fills below the luminance threshold', () => {
87
- // Slate / mid-tone bar fills: WCAG body-text contrast says dark, but bold
88
- // value labels read cleaner in white. These all sit below L=0.42.
89
- expect(pickLabelColor('#94a3b8')).toBe('#ffffff'); // slate-400, L≈0.36
90
- expect(pickLabelColor('#64748b')).toBe('#ffffff'); // slate-500
91
- expect(pickLabelColor('#999999')).toBe('#ffffff'); // mid grey, L≈0.32
92
- expect(pickLabelColor('#e24b4a')).toBe('#ffffff'); // red
93
- expect(pickLabelColor('#d97706')).toBe('#ffffff'); // amber
94
- });
95
-
96
- it('returns dark for genuinely light fills above the luminance threshold', () => {
97
- expect(pickLabelColor('#cbd5e1')).toBe('#111111'); // slate-300
98
- expect(pickLabelColor('#bbbbbb')).toBe('#111111');
99
- expect(pickLabelColor('#dddddd')).toBe('#111111');
100
- });
101
-
102
- it('pivots mid-tone fills to dark text in dark mode (lower threshold)', () => {
103
- // Simultaneous contrast: a mid-tone bar looks lighter on a dark canvas,
104
- // so dark text reads more grounded. Dark mode uses a stricter threshold.
105
- expect(pickLabelColor('#94a3b8', true)).toBe('#111111'); // slate-400
106
- expect(pickLabelColor('#06b6d4', true)).toBe('#111111'); // cyan
107
- expect(pickLabelColor('#999999', true)).toBe('#111111'); // mid grey
108
- // Light mode keeps white on these same fills.
109
- expect(pickLabelColor('#94a3b8', false)).toBe('#ffffff');
110
- expect(pickLabelColor('#06b6d4', false)).toBe('#ffffff');
111
- });
112
-
113
- it('keeps white on saturated fills even in dark mode', () => {
114
- // Saturated palette colors sit below the dark-mode threshold too.
115
- expect(pickLabelColor('#c0392b', true)).toBe('#ffffff'); // red
116
- expect(pickLabelColor('#2563eb', true)).toBe('#ffffff'); // blue
117
- expect(pickLabelColor('#7c3aed', true)).toBe('#ffffff'); // violet
118
- });
119
- });