@recharts/devtools 0.0.18 → 0.0.20
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.
- package/README.md +36 -0
- package/dist/annotations/AnnotationsController.d.ts +7 -1
- package/dist/annotations/AnnotationsController.js +6 -5
- package/dist/annotations/RenderAnnotations.js +17 -4
- package/dist/annotations/annotationInteractionUtils.d.ts +12 -1
- package/dist/annotations/annotationInteractionUtils.js +19 -0
- package/dist/annotations/useAnnotationsManager.js +2 -2
- package/dist/annotations/useSnap.d.ts +16 -16
- package/dist/annotations/useSnap.js +69 -73
- package/dist/components/RechartsAnnotations.js +6 -1
- package/dist/index.d.ts +1 -0
- package/dist/theme/analyze.d.ts +114 -0
- package/dist/theme/analyze.js +189 -0
- package/dist/theme/color.d.ts +53 -0
- package/dist/theme/color.js +90 -0
- package/dist/theme/failures.d.ts +8 -0
- package/dist/theme/failures.js +37 -0
- package/dist/theme/index.d.ts +8 -0
- package/dist/theme/index.js +5 -0
- package/dist/theme/standards.d.ts +28 -0
- package/dist/theme/standards.js +48 -0
- package/dist/theme/suggest.d.ts +10 -0
- package/dist/theme/suggest.js +29 -0
- package/package.json +34 -7
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# @recharts/devtools
|
|
2
2
|
|
|
3
|
+
> **This package is entirely optional.** Recharts works perfectly fine without it. `@recharts/devtools` provides quality of life improvements and development tools to help you build and debug Recharts-based applications more efficiently.
|
|
4
|
+
|
|
3
5
|
Devtools for Recharts.
|
|
4
6
|
|
|
5
7
|
[](https://badge.fury.io/js/@recharts%2Fdevtools)
|
|
@@ -66,3 +68,37 @@ function EditorWithPreview() {
|
|
|
66
68
|
);
|
|
67
69
|
}
|
|
68
70
|
```
|
|
71
|
+
|
|
72
|
+
## Theme accessibility checks
|
|
73
|
+
|
|
74
|
+
`@recharts/devtools/theme` measures how readable the colors of a Recharts theme are. It takes your `RechartsTheme` object as it is. Nothing from React or Recharts runs: the theme is plain data, and Recharts only provides its type (Recharts 3.11.0-canary.6 or newer: earlier versions don't have the full `RechartsTheme` type). All the color math comes from [culori](https://culorijs.org/).
|
|
75
|
+
|
|
76
|
+
For the theme's `pageBackground` (or any backgrounds you pass), and for typical vision plus simulated protanopia, deuteranopia and tritanopia, it checks:
|
|
77
|
+
|
|
78
|
+
| Check | What it measures | Default threshold |
|
|
79
|
+
|---|---|---|
|
|
80
|
+
| `seriesOnBackground` | each series fill and stroke against the page | 3:1, [WCAG 2.2 SC 1.4.11](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) |
|
|
81
|
+
| `seriesVsSeries` | CIEDE2000 difference between every pair of series | none, you choose |
|
|
82
|
+
| `seriesContrast` | WCAG contrast between every pair, for touching marks like pie slices | none, you choose |
|
|
83
|
+
| `textOnBackground` | `typography.color` on the page | 4.5:1, [WCAG 2.2 SC 1.4.3](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) |
|
|
84
|
+
| `seriesAsText` | a series color used for label text on the page | 4.5:1, SC 1.4.3 |
|
|
85
|
+
| `textOnSeries` | `typography.color` on each series fill | 4.5:1, SC 1.4.3 |
|
|
86
|
+
|
|
87
|
+
A failed check usually comes with a fix: the nearest lighter or darker color, with the same hue, that would pass. `fix` is `null` when no lightness passes.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { analyzeTheme, themeFailures } from '@recharts/devtools/theme';
|
|
91
|
+
import { myTheme } from './myTheme';
|
|
92
|
+
|
|
93
|
+
test('my theme is readable', () => {
|
|
94
|
+
const report = analyzeTheme(myTheme, {
|
|
95
|
+
thresholds: { seriesDifference: 10, seriesDifferenceCvd: 2 },
|
|
96
|
+
checks: { textOnSeries: false },
|
|
97
|
+
});
|
|
98
|
+
expect(themeFailures(report)).toEqual([]);
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The guide at https://recharts.github.io/en-US/guide/theme-color-testing/ explains each check and links the standards behind it.
|
|
103
|
+
|
|
104
|
+
The package is ESM only.
|
|
@@ -23,6 +23,12 @@ interface AnnotationsControllerProps {
|
|
|
23
23
|
isAdding: AnnotationType | null;
|
|
24
24
|
selectedAnnotationId: number | null;
|
|
25
25
|
snapMode: SnapMode;
|
|
26
|
+
/**
|
|
27
|
+
* Whether snapping to axis ticks is possible. Tick snapping needs rendered ticks on both axes,
|
|
28
|
+
* so it is unavailable on charts without a rendered <XAxis> and <YAxis>.
|
|
29
|
+
* Defaults to true.
|
|
30
|
+
*/
|
|
31
|
+
tickSnapAvailable?: boolean;
|
|
26
32
|
onStartAdding: (type: AnnotationType) => void;
|
|
27
33
|
onCancelAdding: () => void;
|
|
28
34
|
onDeleteAnnotation: (id: number) => void;
|
|
@@ -36,5 +42,5 @@ interface AnnotationsControllerProps {
|
|
|
36
42
|
* This component renders HTML elements and is meant to be rendered via portal
|
|
37
43
|
* outside the SVG chart context.
|
|
38
44
|
*/
|
|
39
|
-
export declare function AnnotationsController({ annotations, isAdding, selectedAnnotationId, snapMode, onStartAdding, onCancelAdding, onDeleteAnnotation, onUpdateAnnotation, onSelectAnnotation, onSnapModeChange, }: AnnotationsControllerProps): React.JSX.Element;
|
|
45
|
+
export declare function AnnotationsController({ annotations, isAdding, selectedAnnotationId, snapMode, tickSnapAvailable, onStartAdding, onCancelAdding, onDeleteAnnotation, onUpdateAnnotation, onSelectAnnotation, onSnapModeChange, }: AnnotationsControllerProps): React.JSX.Element;
|
|
40
46
|
export {};
|
|
@@ -58,7 +58,8 @@ const labelStyle = {
|
|
|
58
58
|
gap: '1ex',
|
|
59
59
|
marginRight: '2ex',
|
|
60
60
|
};
|
|
61
|
-
|
|
61
|
+
const TICK_SNAP_UNAVAILABLE_REASON = 'Snapping to axis ticks needs a rendered <XAxis> and <YAxis>. Annotations are placed unsnapped.';
|
|
62
|
+
function SnapModeRadioGroup({ snapMode, tickSnapAvailable, onSnapModeChange, }) {
|
|
62
63
|
const name = useId();
|
|
63
64
|
return (React.createElement("div", { style: { marginBottom: '12px' } },
|
|
64
65
|
React.createElement("div", { style: { marginBottom: '6px', fontWeight: 'bold' } }, "Snap to Data:"),
|
|
@@ -68,8 +69,8 @@ function SnapModeRadioGroup({ snapMode, onSnapModeChange, }) {
|
|
|
68
69
|
React.createElement("label", { style: labelStyle },
|
|
69
70
|
React.createElement("input", { type: "radio", name: name, value: "data", checked: snapMode === 'data', onChange: () => onSnapModeChange('data') }),
|
|
70
71
|
"Snap to data points"),
|
|
71
|
-
React.createElement("label", { style: labelStyle },
|
|
72
|
-
React.createElement("input", { type: "radio", name: name, value: "tick", checked: snapMode === 'tick', onChange: () => onSnapModeChange('tick') }),
|
|
72
|
+
React.createElement("label", { style: tickSnapAvailable ? labelStyle : { ...labelStyle, opacity: 0.5 }, title: tickSnapAvailable ? undefined : TICK_SNAP_UNAVAILABLE_REASON },
|
|
73
|
+
React.createElement("input", { type: "radio", name: name, value: "tick", checked: snapMode === 'tick', disabled: !tickSnapAvailable, onChange: () => onSnapModeChange('tick') }),
|
|
73
74
|
"Snap to axis ticks")));
|
|
74
75
|
}
|
|
75
76
|
function AnnotationEditForm({ annotation, handleStyleChange, onUpdateAnnotation, }) {
|
|
@@ -197,7 +198,7 @@ function AnnotationEditForm({ annotation, handleStyleChange, onUpdateAnnotation,
|
|
|
197
198
|
* This component renders HTML elements and is meant to be rendered via portal
|
|
198
199
|
* outside the SVG chart context.
|
|
199
200
|
*/
|
|
200
|
-
export function AnnotationsController({ annotations, isAdding, selectedAnnotationId, snapMode, onStartAdding, onCancelAdding, onDeleteAnnotation, onUpdateAnnotation, onSelectAnnotation, onSnapModeChange, }) {
|
|
201
|
+
export function AnnotationsController({ annotations, isAdding, selectedAnnotationId, snapMode, tickSnapAvailable = true, onStartAdding, onCancelAdding, onDeleteAnnotation, onUpdateAnnotation, onSelectAnnotation, onSnapModeChange, }) {
|
|
201
202
|
const [expandedAnnotationId, setExpandedAnnotationId] = useState(null);
|
|
202
203
|
const handleStyleChange = (annotation, styleKey, value) => {
|
|
203
204
|
onUpdateAnnotation({
|
|
@@ -219,7 +220,7 @@ export function AnnotationsController({ annotations, isAdding, selectedAnnotatio
|
|
|
219
220
|
"Click on the chart to place the annotation",
|
|
220
221
|
(isAdding === 'rectangle' || isAdding === 'freeformLine' || isAdding === 'circle') &&
|
|
221
222
|
' (click twice or drag to define dimensions)'))),
|
|
222
|
-
React.createElement(SnapModeRadioGroup, { snapMode: snapMode, onSnapModeChange: onSnapModeChange }),
|
|
223
|
+
React.createElement(SnapModeRadioGroup, { snapMode: snapMode, tickSnapAvailable: tickSnapAvailable, onSnapModeChange: onSnapModeChange }),
|
|
223
224
|
React.createElement("div", null,
|
|
224
225
|
React.createElement("div", { style: { marginBottom: '6px', fontWeight: 'bold' } },
|
|
225
226
|
"Annotations (",
|
|
@@ -19,7 +19,7 @@ import { Crosshair } from './Crosshair.js';
|
|
|
19
19
|
import { getAnnotationColor } from './annotationColors.js';
|
|
20
20
|
import { useSnap } from './useSnap.js';
|
|
21
21
|
import { DefaultZIndexes, ZIndexLayer } from 'recharts';
|
|
22
|
-
import { DEFAULT_CIRCLE_RADIUS, DEFAULT_RECT_WIDTH, DEFAULT_RECT_HEIGHT, applyAnchorOffset, isDragInteraction, } from './annotationInteractionUtils.js';
|
|
22
|
+
import { DEFAULT_CIRCLE_RADIUS, DEFAULT_RECT_WIDTH, DEFAULT_RECT_HEIGHT, applyAnchorOffset, getPositionType, isDragInteraction, } from './annotationInteractionUtils.js';
|
|
23
23
|
function renderAnnotation(annotation) {
|
|
24
24
|
switch (annotation.type) {
|
|
25
25
|
case 'horizontalLine':
|
|
@@ -78,7 +78,6 @@ function renderFollowerAnnotation(type, snapMode, position, annotationCount, fir
|
|
|
78
78
|
const baseAnnotation = {
|
|
79
79
|
type,
|
|
80
80
|
id: -1, // Temporary ID for follower
|
|
81
|
-
positionType: snapMode === 'none' ? 'pixel' : 'data',
|
|
82
81
|
style: baseStyle,
|
|
83
82
|
label: type === 'label' ? { value: 'Label' } : undefined,
|
|
84
83
|
};
|
|
@@ -102,6 +101,7 @@ function renderFollowerAnnotation(type, snapMode, position, annotationCount, fir
|
|
|
102
101
|
// radius from getDistance(pointA, pointB) using interactionCoordinate.
|
|
103
102
|
return renderAnnotation({
|
|
104
103
|
...baseAnnotation,
|
|
104
|
+
positionType: getPositionType(snapMode, type, firstClickPosition),
|
|
105
105
|
pointA: firstClickPosition,
|
|
106
106
|
pointB: syntheticPoint(fpx + DEFAULT_CIRCLE_RADIUS, fpy),
|
|
107
107
|
});
|
|
@@ -121,7 +121,12 @@ function renderFollowerAnnotation(type, snapMode, position, annotationCount, fir
|
|
|
121
121
|
});
|
|
122
122
|
}
|
|
123
123
|
}
|
|
124
|
-
return renderAnnotation({
|
|
124
|
+
return renderAnnotation({
|
|
125
|
+
...baseAnnotation,
|
|
126
|
+
positionType: getPositionType(snapMode, type, firstClickPosition, position),
|
|
127
|
+
pointA: firstClickPosition,
|
|
128
|
+
pointB: position,
|
|
129
|
+
});
|
|
125
130
|
}
|
|
126
131
|
// Before the first click: show a default-sized preview.
|
|
127
132
|
if (type === 'circle') {
|
|
@@ -129,6 +134,7 @@ function renderFollowerAnnotation(type, snapMode, position, annotationCount, fir
|
|
|
129
134
|
// Pixel mode: real cursor = pointB (edge); anchor offset left so radius = DEFAULT_CIRCLE_RADIUS.
|
|
130
135
|
return renderAnnotation({
|
|
131
136
|
...baseAnnotation,
|
|
137
|
+
positionType: 'pixel',
|
|
132
138
|
pointA: syntheticPoint(px - DEFAULT_CIRCLE_RADIUS, py),
|
|
133
139
|
pointB: position,
|
|
134
140
|
});
|
|
@@ -147,6 +153,7 @@ function renderFollowerAnnotation(type, snapMode, position, annotationCount, fir
|
|
|
147
153
|
// Pixel mode: real cursor = bottom-right corner (pointB); anchor = offset to top-left.
|
|
148
154
|
return renderAnnotation({
|
|
149
155
|
...baseAnnotation,
|
|
156
|
+
positionType: 'pixel',
|
|
150
157
|
pointA: syntheticPoint(px - DEFAULT_RECT_WIDTH, py - DEFAULT_RECT_HEIGHT),
|
|
151
158
|
pointB: position,
|
|
152
159
|
});
|
|
@@ -162,14 +169,20 @@ function renderFollowerAnnotation(type, snapMode, position, annotationCount, fir
|
|
|
162
169
|
}
|
|
163
170
|
if (type === 'freeformLine') {
|
|
164
171
|
// Default short angled stub so the line direction is hinted at.
|
|
172
|
+
// positionType follows pointA only, so the snapped case behaves as before.
|
|
165
173
|
return renderAnnotation({
|
|
166
174
|
...baseAnnotation,
|
|
175
|
+
positionType: getPositionType(snapMode, type, position),
|
|
167
176
|
pointA: position,
|
|
168
177
|
pointB: syntheticPoint(px + 30, py - 15),
|
|
169
178
|
});
|
|
170
179
|
}
|
|
171
180
|
// Single-click annotations (horizontalLine, verticalLine, crosshair, label).
|
|
172
|
-
return renderAnnotation({
|
|
181
|
+
return renderAnnotation({
|
|
182
|
+
...baseAnnotation,
|
|
183
|
+
positionType: getPositionType(snapMode, type, position),
|
|
184
|
+
pointA: position,
|
|
185
|
+
});
|
|
173
186
|
}
|
|
174
187
|
/**
|
|
175
188
|
* Component that renders all annotations and handles mouse events for adding new annotations.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SnapResult } from './useSnap.js';
|
|
2
|
-
import type { AnnotationType, SnapMode } from './types.js';
|
|
2
|
+
import type { AnnotationType, PositionType, SnapMode } from './types.js';
|
|
3
3
|
/**
|
|
4
4
|
* Default dimensions for circle and rectangle pre-click follower previews (pixel mode only).
|
|
5
5
|
*
|
|
@@ -39,3 +39,14 @@ export declare function isDragInteraction(downPos: {
|
|
|
39
39
|
x: number;
|
|
40
40
|
y: number;
|
|
41
41
|
}): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Decides whether an annotation is positioned by data values or by pixels.
|
|
44
|
+
*
|
|
45
|
+
* Data positioning is used only when snapping is on AND the points actually snapped
|
|
46
|
+
* (carry a `dataPoint`). Snapping can fail even when it is on, for example in 'tick' mode
|
|
47
|
+
* on a chart without a rendered <XAxis>/<YAxis>; such points fall back to pixel positioning,
|
|
48
|
+
* otherwise the annotation components would render nothing.
|
|
49
|
+
*
|
|
50
|
+
* Circles only need the centre (pointA) to be snapped; the radius is always in pixels.
|
|
51
|
+
*/
|
|
52
|
+
export declare function getPositionType(snapMode: SnapMode, type: AnnotationType, pointA: SnapResult, pointB?: SnapResult): PositionType;
|
|
@@ -56,3 +56,22 @@ export function isDragInteraction(downPos, upPos) {
|
|
|
56
56
|
const dy = upPos.y - downPos.y;
|
|
57
57
|
return Math.sqrt(dx * dx + dy * dy) > DRAG_THRESHOLD;
|
|
58
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Decides whether an annotation is positioned by data values or by pixels.
|
|
61
|
+
*
|
|
62
|
+
* Data positioning is used only when snapping is on AND the points actually snapped
|
|
63
|
+
* (carry a `dataPoint`). Snapping can fail even when it is on, for example in 'tick' mode
|
|
64
|
+
* on a chart without a rendered <XAxis>/<YAxis>; such points fall back to pixel positioning,
|
|
65
|
+
* otherwise the annotation components would render nothing.
|
|
66
|
+
*
|
|
67
|
+
* Circles only need the centre (pointA) to be snapped; the radius is always in pixels.
|
|
68
|
+
*/
|
|
69
|
+
export function getPositionType(snapMode, type, pointA, pointB) {
|
|
70
|
+
if (snapMode === 'none' || pointA.dataPoint == null) {
|
|
71
|
+
return 'pixel';
|
|
72
|
+
}
|
|
73
|
+
if (type !== 'circle' && pointB != null && pointB.dataPoint == null) {
|
|
74
|
+
return 'pixel';
|
|
75
|
+
}
|
|
76
|
+
return 'data';
|
|
77
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useCallback, useState } from 'react';
|
|
2
2
|
import { DEFAULT_ANNOTATION_STYLE, getAnnotationColor } from './annotationColors.js';
|
|
3
3
|
import { getDistance } from './getDistance.js';
|
|
4
|
-
import { DEFAULT_CIRCLE_RADIUS, DEFAULT_RECT_HEIGHT, DEFAULT_RECT_WIDTH, } from './annotationInteractionUtils.js';
|
|
4
|
+
import { DEFAULT_CIRCLE_RADIUS, DEFAULT_RECT_HEIGHT, DEFAULT_RECT_WIDTH, getPositionType, } from './annotationInteractionUtils.js';
|
|
5
5
|
function annotationFactory(type, color, snapMode, pointA, pointB) {
|
|
6
6
|
const baseStyle = {
|
|
7
7
|
...DEFAULT_ANNOTATION_STYLE,
|
|
@@ -12,7 +12,7 @@ function annotationFactory(type, color, snapMode, pointA, pointB) {
|
|
|
12
12
|
return {
|
|
13
13
|
type,
|
|
14
14
|
id: Date.now(),
|
|
15
|
-
positionType: snapMode
|
|
15
|
+
positionType: getPositionType(snapMode, type, pointA, pointB),
|
|
16
16
|
style: baseStyle,
|
|
17
17
|
pointA,
|
|
18
18
|
pointB,
|
|
@@ -4,13 +4,12 @@
|
|
|
4
4
|
* This uses the Recharts scale hooks to convert between pixel and data coordinates,
|
|
5
5
|
* enabling "magnetic" annotation placement that snaps to actual data points.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* we keep the original coordinate for smooth freeform positioning.
|
|
7
|
+
* Each snap mode reads only the scales it needs: 'none' needs no scales, 'data' needs the
|
|
8
|
+
* data-snap inverse scales and 'tick' needs the tick-snap inverse scales (both plus the forward
|
|
9
|
+
* scales). When the scales a mode needs are unavailable (e.g. 'tick' on a chart without a
|
|
10
|
+
* rendered <XAxis>/<YAxis>, which has no rendered ticks) or the snapped point falls outside the
|
|
11
|
+
* axis, the hook returns the real interaction coordinate, unsnapped, with `snappedCoordinate`
|
|
12
|
+
* and `dataPoint` undefined. Annotations then fall back to pixel positioning.
|
|
14
13
|
*/
|
|
15
14
|
import { MouseEvent } from 'react';
|
|
16
15
|
import { Coordinate } from 'recharts';
|
|
@@ -24,20 +23,21 @@ export interface SnapResult {
|
|
|
24
23
|
} | undefined;
|
|
25
24
|
}
|
|
26
25
|
/**
|
|
27
|
-
* Hook that provides a function to snap
|
|
26
|
+
* Hook that provides a function to snap a mouse event to the nearest data point or axis tick.
|
|
27
|
+
*
|
|
28
|
+
* When snapping is enabled ('data' or 'tick'), this will:
|
|
29
|
+
* 1. Convert pixel coordinates to data values using the inverse snap scale
|
|
30
|
+
* 2. Convert the snapped data values back to pixel coordinates for display
|
|
28
31
|
*
|
|
29
|
-
*
|
|
30
|
-
* 1. Convert pixel coordinates to data values using inverse scale
|
|
31
|
-
* 2. Find the closest data point in the domain (categories)
|
|
32
|
-
* 3. Convert back to pixel coordinates for display
|
|
32
|
+
* If snapping is disabled or not possible, the result carries only the real interaction coordinate.
|
|
33
33
|
*
|
|
34
34
|
* @example
|
|
35
35
|
* ```tsx
|
|
36
|
-
* const
|
|
36
|
+
* const snap = useSnap('data');
|
|
37
37
|
*
|
|
38
|
-
* const handleMouseMove = (
|
|
39
|
-
* const
|
|
40
|
-
* setPosition(
|
|
38
|
+
* const handleMouseMove = (e: React.MouseEvent<SVGGraphicsElement>) => {
|
|
39
|
+
* const { interactionCoordinate, snappedCoordinate } = snap(e);
|
|
40
|
+
* setPosition(snappedCoordinate ?? interactionCoordinate);
|
|
41
41
|
* };
|
|
42
42
|
* ```
|
|
43
43
|
*/
|
|
@@ -4,36 +4,60 @@
|
|
|
4
4
|
* This uses the Recharts scale hooks to convert between pixel and data coordinates,
|
|
5
5
|
* enabling "magnetic" annotation placement that snaps to actual data points.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* we keep the original coordinate for smooth freeform positioning.
|
|
7
|
+
* Each snap mode reads only the scales it needs: 'none' needs no scales, 'data' needs the
|
|
8
|
+
* data-snap inverse scales and 'tick' needs the tick-snap inverse scales (both plus the forward
|
|
9
|
+
* scales). When the scales a mode needs are unavailable (e.g. 'tick' on a chart without a
|
|
10
|
+
* rendered <XAxis>/<YAxis>, which has no rendered ticks) or the snapped point falls outside the
|
|
11
|
+
* axis, the hook returns the real interaction coordinate, unsnapped, with `snappedCoordinate`
|
|
12
|
+
* and `dataPoint` undefined. Annotations then fall back to pixel positioning.
|
|
14
13
|
*/
|
|
15
14
|
import { useCallback } from 'react';
|
|
16
|
-
import { getRelativeCoordinate, useXAxisInverseDataSnapScale, useYAxisInverseDataSnapScale, useXAxisInverseTickSnapScale, useYAxisInverseTickSnapScale, useXAxisScale, useYAxisScale, } from 'recharts';
|
|
15
|
+
import { getRelativeCoordinate, useXAxisInverseScale, useYAxisInverseScale, useXAxisInverseDataSnapScale, useYAxisInverseDataSnapScale, useXAxisInverseTickSnapScale, useYAxisInverseTickSnapScale, useXAxisScale, useYAxisScale, } from 'recharts';
|
|
16
|
+
/**
|
|
17
|
+
* Snaps one axis: pixel -> data value -> snapped pixel.
|
|
18
|
+
*
|
|
19
|
+
* `fallbackInverse` is tried when the snap scale gives a value the forward scale cannot map.
|
|
20
|
+
* This happens with data snapping on a category axis that has no `dataKey` (e.g. an implicit
|
|
21
|
+
* axis on a chart without <XAxis>): Recharts then offers the graphical items' values
|
|
22
|
+
* (e.g. the Line's `uv` values) as snap candidates, while the axis domain is the row indexes.
|
|
23
|
+
* The general inverse scale of a category axis returns the nearest category, which is a
|
|
24
|
+
* data point too.
|
|
25
|
+
*/
|
|
26
|
+
function snapAxis(pixel, inverse, forward, fallbackInverse) {
|
|
27
|
+
for (const candidateInverse of [inverse, fallbackInverse]) {
|
|
28
|
+
if (candidateInverse == null)
|
|
29
|
+
continue;
|
|
30
|
+
const value = candidateInverse(pixel);
|
|
31
|
+
const snappedPixel = forward(value);
|
|
32
|
+
if (snappedPixel != null) {
|
|
33
|
+
return { value, pixel: snappedPixel };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
17
38
|
/**
|
|
18
|
-
* Hook that provides a function to snap
|
|
39
|
+
* Hook that provides a function to snap a mouse event to the nearest data point or axis tick.
|
|
19
40
|
*
|
|
20
|
-
* When
|
|
21
|
-
* 1. Convert pixel coordinates to data values using inverse scale
|
|
22
|
-
* 2.
|
|
23
|
-
*
|
|
41
|
+
* When snapping is enabled ('data' or 'tick'), this will:
|
|
42
|
+
* 1. Convert pixel coordinates to data values using the inverse snap scale
|
|
43
|
+
* 2. Convert the snapped data values back to pixel coordinates for display
|
|
44
|
+
*
|
|
45
|
+
* If snapping is disabled or not possible, the result carries only the real interaction coordinate.
|
|
24
46
|
*
|
|
25
47
|
* @example
|
|
26
48
|
* ```tsx
|
|
27
|
-
* const
|
|
49
|
+
* const snap = useSnap('data');
|
|
28
50
|
*
|
|
29
|
-
* const handleMouseMove = (
|
|
30
|
-
* const
|
|
31
|
-
* setPosition(
|
|
51
|
+
* const handleMouseMove = (e: React.MouseEvent<SVGGraphicsElement>) => {
|
|
52
|
+
* const { interactionCoordinate, snappedCoordinate } = snap(e);
|
|
53
|
+
* setPosition(snappedCoordinate ?? interactionCoordinate);
|
|
32
54
|
* };
|
|
33
55
|
* ```
|
|
34
56
|
*/
|
|
35
57
|
export function useSnap(snapMode) {
|
|
36
58
|
// Get inverse scale functions for converting pixels -> data
|
|
59
|
+
const xInverseScale = useXAxisInverseScale();
|
|
60
|
+
const yInverseScale = useYAxisInverseScale();
|
|
37
61
|
const xInverseDataSnapScale = useXAxisInverseDataSnapScale();
|
|
38
62
|
const yInverseDataSnapScale = useYAxisInverseDataSnapScale();
|
|
39
63
|
const xInverseTickSnapScale = useXAxisInverseTickSnapScale();
|
|
@@ -42,81 +66,53 @@ export function useSnap(snapMode) {
|
|
|
42
66
|
const scaleX = useXAxisScale();
|
|
43
67
|
const scaleY = useYAxisScale();
|
|
44
68
|
return useCallback((e) => {
|
|
45
|
-
if (xInverseDataSnapScale == null ||
|
|
46
|
-
yInverseDataSnapScale == null ||
|
|
47
|
-
xInverseTickSnapScale == null ||
|
|
48
|
-
yInverseTickSnapScale == null ||
|
|
49
|
-
scaleX == null ||
|
|
50
|
-
scaleY == null) {
|
|
51
|
-
/*
|
|
52
|
-
* Scales not available yet (e.g., outside of chart context, or chart not fully initialized)
|
|
53
|
-
* Just return zeroes to avoid errors
|
|
54
|
-
*/
|
|
55
|
-
return {
|
|
56
|
-
interactionCoordinate: { x: 0, y: 0 },
|
|
57
|
-
snappedCoordinate: undefined,
|
|
58
|
-
dataPoint: undefined,
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
69
|
/*
|
|
62
70
|
* Here we get pixel coordinates relative to the chart area (accounting for transforms)
|
|
63
71
|
* These are exact mouse interaction coordinates.
|
|
64
72
|
* Next, we need to "snap" these to the nearest data point if snapMode is enabled.
|
|
65
73
|
*/
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
snappedDataPoint = {
|
|
76
|
-
x: xInverseTickSnapScale(interactionCoordinate.relativeX),
|
|
77
|
-
y: yInverseTickSnapScale(interactionCoordinate.relativeY),
|
|
78
|
-
};
|
|
74
|
+
const relative = getRelativeCoordinate(e);
|
|
75
|
+
const interactionCoordinate = { x: relative.relativeX, y: relative.relativeY };
|
|
76
|
+
const unsnapped = {
|
|
77
|
+
interactionCoordinate,
|
|
78
|
+
snappedCoordinate: undefined,
|
|
79
|
+
dataPoint: undefined,
|
|
80
|
+
};
|
|
81
|
+
if (snapMode === 'none') {
|
|
82
|
+
return unsnapped;
|
|
79
83
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
84
|
+
/*
|
|
85
|
+
* Each snap mode needs only its own inverse scales plus the forward scales.
|
|
86
|
+
* Any of them can be missing: for example, charts without a rendered <XAxis>/<YAxis>
|
|
87
|
+
* have no rendered ticks, so the tick-snap scales are undefined.
|
|
88
|
+
* In that case we keep the real (unsnapped) interaction coordinate.
|
|
89
|
+
*/
|
|
90
|
+
const xInverse = snapMode === 'data' ? xInverseDataSnapScale : xInverseTickSnapScale;
|
|
91
|
+
const yInverse = snapMode === 'data' ? yInverseDataSnapScale : yInverseTickSnapScale;
|
|
92
|
+
if (xInverse == null || yInverse == null || scaleX == null || scaleY == null) {
|
|
93
|
+
return unsnapped;
|
|
90
94
|
}
|
|
91
95
|
/*
|
|
92
|
-
* Converts snapped data point back to pixel coordinates.
|
|
96
|
+
* Converts the snapped data point back to pixel coordinates.
|
|
93
97
|
* Some components will read the snapped data point to display values, while others will use the snapped pixel coordinates for positioning.
|
|
94
98
|
* We return here both the snapped data point (for display) and the snapped pixel coordinates (for positioning) for convenience.
|
|
95
99
|
* If you are using ReferenceLine/ReferenceDot, you can skip this step and use the snappedDataPoint directly.
|
|
96
100
|
*/
|
|
97
|
-
const snappedX =
|
|
98
|
-
const snappedY =
|
|
101
|
+
const snappedX = snapAxis(interactionCoordinate.x, xInverse, scaleX, snapMode === 'data' ? xInverseScale : undefined);
|
|
102
|
+
const snappedY = snapAxis(interactionCoordinate.y, yInverse, scaleY, snapMode === 'data' ? yInverseScale : undefined);
|
|
99
103
|
if (snappedX == null || snappedY == null) {
|
|
100
104
|
// If the snapped data point is outside the chart area, just return the original interaction coordinates
|
|
101
|
-
return
|
|
102
|
-
interactionCoordinate: {
|
|
103
|
-
x: interactionCoordinate.relativeX,
|
|
104
|
-
y: interactionCoordinate.relativeY,
|
|
105
|
-
},
|
|
106
|
-
snappedCoordinate: undefined,
|
|
107
|
-
dataPoint: undefined,
|
|
108
|
-
};
|
|
105
|
+
return unsnapped;
|
|
109
106
|
}
|
|
110
107
|
return {
|
|
111
|
-
interactionCoordinate
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
},
|
|
115
|
-
snappedCoordinate: { x: snappedX, y: snappedY },
|
|
116
|
-
dataPoint: snappedDataPoint,
|
|
108
|
+
interactionCoordinate,
|
|
109
|
+
snappedCoordinate: { x: snappedX.pixel, y: snappedY.pixel },
|
|
110
|
+
dataPoint: { x: snappedX.value, y: snappedY.value },
|
|
117
111
|
};
|
|
118
112
|
}, [
|
|
119
113
|
snapMode,
|
|
114
|
+
xInverseScale,
|
|
115
|
+
yInverseScale,
|
|
120
116
|
xInverseDataSnapScale,
|
|
121
117
|
yInverseDataSnapScale,
|
|
122
118
|
xInverseTickSnapScale,
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import React from 'react';
|
|
19
19
|
import { createPortal } from 'react-dom';
|
|
20
|
+
import { useXAxisInverseTickSnapScale, useYAxisInverseTickSnapScale } from 'recharts';
|
|
20
21
|
import { RECHARTS_ANNOTATIONS_PORTAL_ID } from '../constants.js';
|
|
21
22
|
import { useRechartsDevtoolsContext } from '../context/RechartsDevtoolsContext.js';
|
|
22
23
|
import { AnnotationsController, RenderAnnotations, useAnnotationsManager } from '../annotations/index.js';
|
|
@@ -26,6 +27,10 @@ export const RechartsAnnotations = () => {
|
|
|
26
27
|
const portalId = contextId ? `${contextId}-annotations` : RECHARTS_ANNOTATIONS_PORTAL_ID;
|
|
27
28
|
const [container, setContainer] = React.useState(null);
|
|
28
29
|
const annotationsManager = useAnnotationsManager();
|
|
30
|
+
// Tick snapping needs rendered ticks, which only a rendered <XAxis>/<YAxis> provides.
|
|
31
|
+
const xTickSnapScale = useXAxisInverseTickSnapScale();
|
|
32
|
+
const yTickSnapScale = useYAxisInverseTickSnapScale();
|
|
33
|
+
const tickSnapAvailable = xTickSnapScale != null && yTickSnapScale != null;
|
|
29
34
|
React.useEffect(() => {
|
|
30
35
|
const el = document.getElementById(portalId);
|
|
31
36
|
setContainer(el);
|
|
@@ -34,5 +39,5 @@ export const RechartsAnnotations = () => {
|
|
|
34
39
|
React.createElement(RenderAnnotations, { annotations: annotationsManager.annotations, isAdding: annotationsManager.isAdding, followerPosition: annotationsManager.followerPosition, firstClickPosition: annotationsManager.firstClickPosition, snapMode: annotationsManager.snapMode, onChartClick: annotationsManager.onChartClick, onChartMouseDown: annotationsManager.onChartMouseDown, onChartMouseUp: annotationsManager.onChartMouseUp, onChartMouseMove: annotationsManager.onChartMouseMove, onChartMouseLeave: annotationsManager.onChartMouseLeave }),
|
|
35
40
|
container &&
|
|
36
41
|
createPortal(React.createElement("div", { className: "recharts-annotations", style: { fontFamily: 'monospace', fontSize: '12px' } },
|
|
37
|
-
React.createElement(AnnotationsController, { annotations: annotationsManager.annotations, isAdding: annotationsManager.isAdding, selectedAnnotationId: annotationsManager.selectedAnnotationId, snapMode: annotationsManager.snapMode, onStartAdding: annotationsManager.startAddingAnnotation, onCancelAdding: annotationsManager.cancelAddingAnnotation, onDeleteAnnotation: annotationsManager.deleteAnnotation, onUpdateAnnotation: annotationsManager.updateAnnotation, onSelectAnnotation: annotationsManager.selectAnnotation, onSnapModeChange: annotationsManager.setSnapMode })), container)));
|
|
42
|
+
React.createElement(AnnotationsController, { annotations: annotationsManager.annotations, isAdding: annotationsManager.isAdding, selectedAnnotationId: annotationsManager.selectedAnnotationId, snapMode: annotationsManager.snapMode, tickSnapAvailable: tickSnapAvailable, onStartAdding: annotationsManager.startAddingAnnotation, onCancelAdding: annotationsManager.cancelAddingAnnotation, onDeleteAnnotation: annotationsManager.deleteAnnotation, onUpdateAnnotation: annotationsManager.updateAnnotation, onSelectAnnotation: annotationsManager.selectAnnotation, onSnapModeChange: annotationsManager.setSnapMode })), container)));
|
|
38
43
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export { between, random } from './random.js';
|
|
|
2
2
|
export { generateMockData } from './generateMockData.js';
|
|
3
3
|
export type { MockDataType } from './generateMockData.js';
|
|
4
4
|
export { generateMockMarketData } from './generateMockMarketData.js';
|
|
5
|
+
export type { MarketCandle } from './generateMockMarketData.js';
|
|
5
6
|
export { RechartsDevtools } from './components/RechartsDevtools.js';
|
|
6
7
|
export { RechartsAnnotations } from './components/RechartsAnnotations.js';
|
|
7
8
|
export { RechartsDevtoolsPortal, RechartsAnnotationsPortal, RechartsDevtoolsContext, } from './context/RechartsDevtoolsContext.js';
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { RechartsTheme } from 'recharts';
|
|
2
|
+
import { type Vision } from './color.js';
|
|
3
|
+
import { type CriterionId } from './standards.js';
|
|
4
|
+
/**
|
|
5
|
+
* - `fill`: the series fill, painted at its `fillOpacity` over the page. Bars, areas, pie slices.
|
|
6
|
+
* - `stroke`: the series stroke, fully opaque. Lines, outlines, dots.
|
|
7
|
+
*/
|
|
8
|
+
export type Mark = 'fill' | 'stroke';
|
|
9
|
+
/**
|
|
10
|
+
* The analysis that produced a `CheckResult`:
|
|
11
|
+
* - `seriesOnBackground`: non-text contrast between each series mark and its background.
|
|
12
|
+
* - `seriesVsSeries`: CIEDE2000 color difference between each pair of series marks.
|
|
13
|
+
* - `seriesContrast`: non-text contrast between each pair of series marks.
|
|
14
|
+
* - `textOnBackground`: text contrast between the label color and its background.
|
|
15
|
+
* - `seriesAsText`: text contrast between each series stroke and its background.
|
|
16
|
+
* - `textOnSeries`: text contrast between the label color and each series fill.
|
|
17
|
+
*
|
|
18
|
+
* Checks run for each configured background and simulated vision where applicable.
|
|
19
|
+
*/
|
|
20
|
+
export type CheckId = 'seriesOnBackground' | 'seriesVsSeries' | 'seriesContrast' | 'textOnBackground' | 'seriesAsText' | 'textOnSeries';
|
|
21
|
+
export type Thresholds = {
|
|
22
|
+
/** Series against the page. Defaults to 3, from WCAG SC 1.4.11. */
|
|
23
|
+
nonTextContrast: number;
|
|
24
|
+
/** Labels against what they sit on. Defaults to 4.5, from WCAG SC 1.4.3. See `WCAG_CONTRAST` for the others. */
|
|
25
|
+
textContrast: number;
|
|
26
|
+
/**
|
|
27
|
+
* Smallest CIEDE2000 difference between two series in typical vision.
|
|
28
|
+
* No standard defines one, so there is no default: without it the check only reports values.
|
|
29
|
+
*/
|
|
30
|
+
seriesDifference: number | null;
|
|
31
|
+
/** Like `seriesDifference`, under simulated color vision deficiencies. No default either. */
|
|
32
|
+
seriesDifferenceCvd: number | null;
|
|
33
|
+
/**
|
|
34
|
+
* WCAG contrast between two series, for charts where series touch, like pie slices without borders.
|
|
35
|
+
* No default: WCAG SC 1.4.11 asks for 3:1 only when nothing else separates them.
|
|
36
|
+
*/
|
|
37
|
+
seriesContrast: number | null;
|
|
38
|
+
};
|
|
39
|
+
export type ThemeCheckOptions = {
|
|
40
|
+
/**
|
|
41
|
+
* The backgrounds to check on, by name. Defaults to `{ page: theme.pageBackground }`, falling back to
|
|
42
|
+
* `theme.chart.backgroundColor`. Pass more when the same theme shows on several surfaces, like cards.
|
|
43
|
+
*/
|
|
44
|
+
backgrounds?: Readonly<Record<string, string>>;
|
|
45
|
+
/** Defaults to all four. */
|
|
46
|
+
visions?: ReadonlyArray<Vision>;
|
|
47
|
+
/** From 0 to 1, see `simulateVision`. Defaults to 1. */
|
|
48
|
+
severity?: number;
|
|
49
|
+
/** Defaults to both. */
|
|
50
|
+
marks?: ReadonlyArray<Mark>;
|
|
51
|
+
thresholds?: Partial<Thresholds>;
|
|
52
|
+
/**
|
|
53
|
+
* Turn off checks that don't apply to your charts. Every check is on by default, except that
|
|
54
|
+
* `textOnBackground` and `textOnSeries` only run when `theme.typography.color` is set.
|
|
55
|
+
*/
|
|
56
|
+
checks?: Partial<Record<CheckId, boolean>>;
|
|
57
|
+
};
|
|
58
|
+
/** One series, as read from `theme.graphicalItems`. */
|
|
59
|
+
export type ThemeSeries = {
|
|
60
|
+
index: number;
|
|
61
|
+
fill: string;
|
|
62
|
+
stroke: string;
|
|
63
|
+
fillOpacity: number;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* A color that would make a failed check pass: the nearest lighter or darker color with the same hue.
|
|
67
|
+
* Changing it may affect other checks, so run the analysis again after you change it.
|
|
68
|
+
*/
|
|
69
|
+
export type Fix = {
|
|
70
|
+
/** Which color to change: a series (its fill or stroke, see `CheckResult.mark`) or the label color. */
|
|
71
|
+
target: 'series' | 'text';
|
|
72
|
+
/** The zero-based index of the series to change, or `null` for the label color. */
|
|
73
|
+
series: number | null;
|
|
74
|
+
from: string;
|
|
75
|
+
to: string;
|
|
76
|
+
};
|
|
77
|
+
export type CheckResult = {
|
|
78
|
+
check: CheckId;
|
|
79
|
+
criterion: CriterionId;
|
|
80
|
+
/** The name of the background, as a key of `ThemeReport.backgrounds`. */
|
|
81
|
+
background: string;
|
|
82
|
+
vision: Vision;
|
|
83
|
+
mark: Mark | null;
|
|
84
|
+
/** Zero-based indexes of the series involved. */
|
|
85
|
+
series: ReadonlyArray<number>;
|
|
86
|
+
/** The two colors compared, as the reader with this vision sees them. */
|
|
87
|
+
colors: readonly [string, string];
|
|
88
|
+
/** A contrast ratio, or a CIEDE2000 difference for `seriesVsSeries`. */
|
|
89
|
+
value: number;
|
|
90
|
+
threshold: number | null;
|
|
91
|
+
/** `null` when there is no threshold, so the result is informational. */
|
|
92
|
+
passes: boolean | null;
|
|
93
|
+
/** Only on failed checks, and `null` when no lighter or darker color passes. */
|
|
94
|
+
fix: Fix | null;
|
|
95
|
+
};
|
|
96
|
+
export type ThemeReport = {
|
|
97
|
+
series: ReadonlyArray<ThemeSeries>;
|
|
98
|
+
backgrounds: Readonly<Record<string, string>>;
|
|
99
|
+
/** `theme.typography.color`, or `null` when the theme has none or the label checks are off. */
|
|
100
|
+
text: string | null;
|
|
101
|
+
visions: ReadonlyArray<Vision>;
|
|
102
|
+
severity: number;
|
|
103
|
+
marks: ReadonlyArray<Mark>;
|
|
104
|
+
thresholds: Thresholds;
|
|
105
|
+
checks: ReadonlyArray<CheckResult>;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Measures how readable the colors of a Recharts theme are: series against the page, series against
|
|
109
|
+
* each other, and labels on the page and on the series, for every background and every simulated vision.
|
|
110
|
+
*
|
|
111
|
+
* Nothing from Recharts runs here: the theme is plain data, and its type is only used at compile time.
|
|
112
|
+
* The result is plain data too. Use `themeFailures` to turn it into test assertions.
|
|
113
|
+
*/
|
|
114
|
+
export declare function analyzeTheme(theme: RechartsTheme, options?: ThemeCheckOptions): ThemeReport;
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { colorDifference, composite, contrastRatio, parseColor, simulateVision, toHex, VISIONS, } from './color.js';
|
|
2
|
+
import { WCAG_CONTRAST } from './standards.js';
|
|
3
|
+
import { nearestPassingColor } from './suggest.js';
|
|
4
|
+
const DEFAULT_THRESHOLDS = {
|
|
5
|
+
nonTextContrast: WCAG_CONTRAST.nonText,
|
|
6
|
+
textContrast: WCAG_CONTRAST.text,
|
|
7
|
+
seriesDifference: null,
|
|
8
|
+
seriesDifferenceCvd: null,
|
|
9
|
+
seriesContrast: null,
|
|
10
|
+
};
|
|
11
|
+
/** The checks that need `theme.typography.color`. */
|
|
12
|
+
const LABEL_CHECKS = ['textOnBackground', 'textOnSeries'];
|
|
13
|
+
/**
|
|
14
|
+
* One entry per `graphicalItems` item, with the fill falling back to the stroke and the other way round.
|
|
15
|
+
* A fill object (gradient or pattern) counts as its solid `color`, the one recharts uses for Tooltip and labels.
|
|
16
|
+
* Without a `color` it has no color of its own, so the stroke is used, as recharts does.
|
|
17
|
+
*/
|
|
18
|
+
function readSeries(theme) {
|
|
19
|
+
return theme.graphicalItems.map((item, index) => {
|
|
20
|
+
const fill = typeof item.fill === 'string' ? item.fill : item.fill?.color;
|
|
21
|
+
const color = fill ?? item.stroke;
|
|
22
|
+
if (color == null) {
|
|
23
|
+
throw new Error(`graphicalItems[${index}] has no fill or stroke color`);
|
|
24
|
+
}
|
|
25
|
+
const opacity = Number(item.fillOpacity ?? 1);
|
|
26
|
+
return {
|
|
27
|
+
index,
|
|
28
|
+
fill: color,
|
|
29
|
+
stroke: item.stroke ?? color,
|
|
30
|
+
fillOpacity: Number.isFinite(opacity) ? opacity : 1,
|
|
31
|
+
};
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** `options.backgrounds`, or else the theme's own page background. */
|
|
35
|
+
function readBackgrounds(theme, options) {
|
|
36
|
+
if (options.backgrounds != null) {
|
|
37
|
+
return options.backgrounds;
|
|
38
|
+
}
|
|
39
|
+
const chartBackground = theme.chart?.backgroundColor;
|
|
40
|
+
const page = theme.pageBackground ?? (typeof chartBackground === 'string' ? chartBackground : undefined);
|
|
41
|
+
if (page == null) {
|
|
42
|
+
throw new Error('The theme has no pageBackground; set it, or pass options.backgrounds');
|
|
43
|
+
}
|
|
44
|
+
return { page };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Measures how readable the colors of a Recharts theme are: series against the page, series against
|
|
48
|
+
* each other, and labels on the page and on the series, for every background and every simulated vision.
|
|
49
|
+
*
|
|
50
|
+
* Nothing from Recharts runs here: the theme is plain data, and its type is only used at compile time.
|
|
51
|
+
* The result is plain data too. Use `themeFailures` to turn it into test assertions.
|
|
52
|
+
*/
|
|
53
|
+
export function analyzeTheme(theme, options = {}) {
|
|
54
|
+
const visions = options.visions ?? VISIONS;
|
|
55
|
+
const severity = options.severity ?? 1;
|
|
56
|
+
const marks = options.marks ?? ['fill', 'stroke'];
|
|
57
|
+
const thresholds = { ...DEFAULT_THRESHOLDS, ...options.thresholds };
|
|
58
|
+
const typography = theme.typography?.color;
|
|
59
|
+
const text = typeof typography === 'string' ? typography : null;
|
|
60
|
+
const enabled = (check) => options.checks?.[check] !== false && (text != null || !LABEL_CHECKS.includes(check));
|
|
61
|
+
const series = readSeries(theme);
|
|
62
|
+
const backgrounds = readBackgrounds(theme, options);
|
|
63
|
+
const checks = [];
|
|
64
|
+
for (const [background, backgroundColor] of Object.entries(backgrounds)) {
|
|
65
|
+
const page = parseColor(backgroundColor);
|
|
66
|
+
if (page.alpha !== undefined && page.alpha < 1) {
|
|
67
|
+
throw new Error(`Background "${background}" must be opaque, got "${backgroundColor}"`);
|
|
68
|
+
}
|
|
69
|
+
const pageHex = toHex(page);
|
|
70
|
+
// What a series looks like on this page in typical vision, before simulation.
|
|
71
|
+
const paint = (s, mark, color = mark === 'fill' ? s.fill : s.stroke) => toHex(composite(color, mark === 'fill' ? s.fillOpacity : 1, page));
|
|
72
|
+
const label = text == null ? null : toHex(composite(text, 1, page));
|
|
73
|
+
for (const vision of visions) {
|
|
74
|
+
const see = (color) => toHex(simulateVision(color, vision, severity));
|
|
75
|
+
const seenPage = see(pageHex);
|
|
76
|
+
const seenLabel = label == null ? null : see(label);
|
|
77
|
+
/**
|
|
78
|
+
* Records one measurement. `measure` takes the color under test as it is in the theme, so the same
|
|
79
|
+
* function finds a fix when the check fails.
|
|
80
|
+
*/
|
|
81
|
+
const add = (result, criterion, target, measure) => {
|
|
82
|
+
const value = measure(target.from);
|
|
83
|
+
const passes = result.threshold == null ? null : value >= result.threshold;
|
|
84
|
+
const threshold = result.threshold;
|
|
85
|
+
const to = passes === false && threshold != null
|
|
86
|
+
? nearestPassingColor(target.from, (hex) => measure(hex) >= threshold)
|
|
87
|
+
: null;
|
|
88
|
+
checks.push({
|
|
89
|
+
...result,
|
|
90
|
+
value,
|
|
91
|
+
criterion,
|
|
92
|
+
passes,
|
|
93
|
+
fix: to == null ? null : { ...target, to },
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
for (const mark of marks) {
|
|
97
|
+
const seen = series.map((s) => see(paint(s, mark)));
|
|
98
|
+
const own = (s) => (mark === 'fill' ? s.fill : s.stroke);
|
|
99
|
+
const seriesFix = (s) => ({ target: 'series', series: s.index, from: own(s) });
|
|
100
|
+
if (enabled('seriesOnBackground')) {
|
|
101
|
+
series.forEach((s, i) => add({
|
|
102
|
+
check: 'seriesOnBackground',
|
|
103
|
+
background,
|
|
104
|
+
vision,
|
|
105
|
+
mark,
|
|
106
|
+
series: [i],
|
|
107
|
+
colors: [seen[i], seenPage],
|
|
108
|
+
threshold: thresholds.nonTextContrast,
|
|
109
|
+
}, 'wcag-1.4.11', seriesFix(s), (color) => contrastRatio(see(paint(s, mark, color)), seenPage)));
|
|
110
|
+
}
|
|
111
|
+
for (let i = 0; i < series.length; i++) {
|
|
112
|
+
for (let j = i + 1; j < series.length; j++) {
|
|
113
|
+
// A fix changes the second series of the pair, and keeps the first one as it is.
|
|
114
|
+
const second = series[j];
|
|
115
|
+
if (enabled('seriesVsSeries')) {
|
|
116
|
+
add({
|
|
117
|
+
check: 'seriesVsSeries',
|
|
118
|
+
background,
|
|
119
|
+
vision,
|
|
120
|
+
mark,
|
|
121
|
+
series: [i, j],
|
|
122
|
+
colors: [seen[i], seen[j]],
|
|
123
|
+
threshold: vision === 'normal'
|
|
124
|
+
? thresholds.seriesDifference
|
|
125
|
+
: thresholds.seriesDifferenceCvd,
|
|
126
|
+
}, 'ciede2000', seriesFix(second), (color) => colorDifference(seen[i], see(paint(second, mark, color))));
|
|
127
|
+
}
|
|
128
|
+
if (enabled('seriesContrast')) {
|
|
129
|
+
add({
|
|
130
|
+
check: 'seriesContrast',
|
|
131
|
+
background,
|
|
132
|
+
vision,
|
|
133
|
+
mark,
|
|
134
|
+
series: [i, j],
|
|
135
|
+
colors: [seen[i], seen[j]],
|
|
136
|
+
threshold: thresholds.seriesContrast,
|
|
137
|
+
}, 'wcag-1.4.11', seriesFix(second), (color) => contrastRatio(seen[i], see(paint(second, mark, color))));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (mark === 'stroke' && enabled('seriesAsText')) {
|
|
142
|
+
series.forEach((s, i) => add({
|
|
143
|
+
check: 'seriesAsText',
|
|
144
|
+
background,
|
|
145
|
+
vision,
|
|
146
|
+
mark,
|
|
147
|
+
series: [i],
|
|
148
|
+
colors: [seen[i], seenPage],
|
|
149
|
+
threshold: thresholds.textContrast,
|
|
150
|
+
}, 'wcag-1.4.3', seriesFix(s), (color) => contrastRatio(see(paint(s, mark, color)), seenPage)));
|
|
151
|
+
}
|
|
152
|
+
if (mark === 'fill' && text != null && seenLabel != null && enabled('textOnSeries')) {
|
|
153
|
+
series.forEach((s, i) => add({
|
|
154
|
+
check: 'textOnSeries',
|
|
155
|
+
background,
|
|
156
|
+
vision,
|
|
157
|
+
mark,
|
|
158
|
+
series: [i],
|
|
159
|
+
colors: [seenLabel, seen[i]],
|
|
160
|
+
threshold: thresholds.textContrast,
|
|
161
|
+
}, 'wcag-1.4.3',
|
|
162
|
+
// The label color is shared by every series, so the fix is a label color for this one series.
|
|
163
|
+
{ target: 'text', series: null, from: text }, (color) => contrastRatio(see(toHex(composite(color, 1, page))), seen[i])));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (text != null && seenLabel != null && enabled('textOnBackground')) {
|
|
167
|
+
add({
|
|
168
|
+
check: 'textOnBackground',
|
|
169
|
+
background,
|
|
170
|
+
vision,
|
|
171
|
+
mark: null,
|
|
172
|
+
series: [],
|
|
173
|
+
colors: [seenLabel, seenPage],
|
|
174
|
+
threshold: thresholds.textContrast,
|
|
175
|
+
}, 'wcag-1.4.3', { target: 'text', series: null, from: text }, (color) => contrastRatio(see(toHex(composite(color, 1, page))), seenPage));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
series,
|
|
181
|
+
backgrounds: { ...backgrounds },
|
|
182
|
+
text: enabled('textOnBackground') || enabled('textOnSeries') ? text : null,
|
|
183
|
+
visions: [...visions],
|
|
184
|
+
severity,
|
|
185
|
+
marks: [...marks],
|
|
186
|
+
thresholds,
|
|
187
|
+
checks,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thin wrappers over culori, so that every measurement in this module goes through one
|
|
3
|
+
* well-tested library instead of hand-written color math.
|
|
4
|
+
* @see {@link https://culorijs.org/api/}
|
|
5
|
+
*/
|
|
6
|
+
import { type Color, type Rgb } from 'culori';
|
|
7
|
+
/**
|
|
8
|
+
* How a reader sees colors: typical color vision, or one of the three dichromacies
|
|
9
|
+
* that Machado, Oliveira and Fernandes (2009) model.
|
|
10
|
+
*/
|
|
11
|
+
export type Vision = 'normal' | 'protanopia' | 'deuteranopia' | 'tritanopia';
|
|
12
|
+
export declare const VISIONS: ReadonlyArray<Vision>;
|
|
13
|
+
/** Any CSS color string that culori parses, or a culori color object. */
|
|
14
|
+
export type ColorInput = string | Color;
|
|
15
|
+
/**
|
|
16
|
+
* Parses a color into sRGB.
|
|
17
|
+
* @throws when the color cannot be parsed. `light-dark()` and CSS variables are not colors on their own;
|
|
18
|
+
* resolve them to the light or the dark value first.
|
|
19
|
+
*/
|
|
20
|
+
export declare function parseColor(color: ColorInput): Rgb;
|
|
21
|
+
/** Formats a color as `#rrggbb`, dropping alpha. */
|
|
22
|
+
export declare function toHex(color: ColorInput): string;
|
|
23
|
+
/**
|
|
24
|
+
* The color a reader sees when `color` is painted at `opacity` over an opaque `background`.
|
|
25
|
+
* Alpha already present in `color` multiplies with `opacity`.
|
|
26
|
+
* This is simple alpha compositing in sRGB, which is what browsers do for SVG `fill-opacity`.
|
|
27
|
+
* @see {@link https://www.w3.org/TR/compositing-1/#simplealphacompositing}
|
|
28
|
+
*/
|
|
29
|
+
export declare function composite(color: ColorInput, opacity: number, background: ColorInput): Rgb;
|
|
30
|
+
/**
|
|
31
|
+
* WCAG 2 contrast ratio, from 1 to 21. The order of the two colors does not matter.
|
|
32
|
+
* @see {@link https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio}
|
|
33
|
+
*/
|
|
34
|
+
export declare function contrastRatio(a: ColorInput, b: ColorInput): number;
|
|
35
|
+
/**
|
|
36
|
+
* CIEDE2000 color difference (ΔE00). Larger means easier to tell apart.
|
|
37
|
+
* @see {@link https://hajim.rochester.edu/ece/sites/gsharma/ciede2000/}
|
|
38
|
+
*/
|
|
39
|
+
export declare function colorDifference(a: ColorInput, b: ColorInput): number;
|
|
40
|
+
/**
|
|
41
|
+
* Approximates how a reader with a color vision deficiency sees `color`.
|
|
42
|
+
*
|
|
43
|
+
* The matrices are culori's, from Machado, Oliveira and Fernandes (2009). culori multiplies them with
|
|
44
|
+
* gamma-encoded sRGB, but the model describes light reaching the cones, which adds up linearly. The R
|
|
45
|
+
* `colorspace` package, which culori took the matrices from, fixed the same issue in version 2.1-0.
|
|
46
|
+
* So this function hands culori's filter linear-light channels and re-encodes the result.
|
|
47
|
+
* @see {@link https://doi.org/10.1109/TVCG.2009.113}
|
|
48
|
+
* @see {@link https://www.zeileis.org/news/simulate_cvd/}
|
|
49
|
+
*
|
|
50
|
+
* @param severity from 0 (typical vision) to 1 (dichromacy, the default). Values in between approximate
|
|
51
|
+
* anomalous trichromacy. culori rounds them to the nearest 0.1, the steps that Machado et al. published.
|
|
52
|
+
*/
|
|
53
|
+
export declare function simulateVision(color: ColorInput, vision: Vision, severity?: number): Rgb;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thin wrappers over culori, so that every measurement in this module goes through one
|
|
3
|
+
* well-tested library instead of hand-written color math.
|
|
4
|
+
* @see {@link https://culorijs.org/api/}
|
|
5
|
+
*/
|
|
6
|
+
import { blend, clampRgb, converter, differenceCiede2000, filterDeficiencyDeuter, filterDeficiencyProt, filterDeficiencyTrit, formatHex, parse, wcagContrast, } from 'culori';
|
|
7
|
+
export const VISIONS = [
|
|
8
|
+
'normal',
|
|
9
|
+
'protanopia',
|
|
10
|
+
'deuteranopia',
|
|
11
|
+
'tritanopia',
|
|
12
|
+
];
|
|
13
|
+
const toRgb = converter('rgb');
|
|
14
|
+
const toLrgb = converter('lrgb');
|
|
15
|
+
const ciede2000 = differenceCiede2000();
|
|
16
|
+
/**
|
|
17
|
+
* Parses a color into sRGB.
|
|
18
|
+
* @throws when the color cannot be parsed. `light-dark()` and CSS variables are not colors on their own;
|
|
19
|
+
* resolve them to the light or the dark value first.
|
|
20
|
+
*/
|
|
21
|
+
export function parseColor(color) {
|
|
22
|
+
const parsed = typeof color === 'string' ? parse(color) : color;
|
|
23
|
+
if (parsed === undefined) {
|
|
24
|
+
throw new Error(`Cannot parse color "${String(color)}"`);
|
|
25
|
+
}
|
|
26
|
+
return toRgb(parsed);
|
|
27
|
+
}
|
|
28
|
+
/** Formats a color as `#rrggbb`, dropping alpha. */
|
|
29
|
+
export function toHex(color) {
|
|
30
|
+
return formatHex(parseColor(color));
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The color a reader sees when `color` is painted at `opacity` over an opaque `background`.
|
|
34
|
+
* Alpha already present in `color` multiplies with `opacity`.
|
|
35
|
+
* This is simple alpha compositing in sRGB, which is what browsers do for SVG `fill-opacity`.
|
|
36
|
+
* @see {@link https://www.w3.org/TR/compositing-1/#simplealphacompositing}
|
|
37
|
+
*/
|
|
38
|
+
export function composite(color, opacity, background) {
|
|
39
|
+
const foreground = parseColor(color);
|
|
40
|
+
const alpha = (foreground.alpha ?? 1) * opacity;
|
|
41
|
+
const backdrop = { ...parseColor(background), alpha: 1 };
|
|
42
|
+
return toRgb(blend([backdrop, { ...foreground, alpha }], 'normal', 'rgb'));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* WCAG 2 contrast ratio, from 1 to 21. The order of the two colors does not matter.
|
|
46
|
+
* @see {@link https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio}
|
|
47
|
+
*/
|
|
48
|
+
export function contrastRatio(a, b) {
|
|
49
|
+
return wcagContrast(parseColor(a), parseColor(b));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* CIEDE2000 color difference (ΔE00). Larger means easier to tell apart.
|
|
53
|
+
* @see {@link https://hajim.rochester.edu/ece/sites/gsharma/ciede2000/}
|
|
54
|
+
*/
|
|
55
|
+
export function colorDifference(a, b) {
|
|
56
|
+
return ciede2000(parseColor(a), parseColor(b));
|
|
57
|
+
}
|
|
58
|
+
const FILTERS = {
|
|
59
|
+
protanopia: filterDeficiencyProt,
|
|
60
|
+
deuteranopia: filterDeficiencyDeuter,
|
|
61
|
+
tritanopia: filterDeficiencyTrit,
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Approximates how a reader with a color vision deficiency sees `color`.
|
|
65
|
+
*
|
|
66
|
+
* The matrices are culori's, from Machado, Oliveira and Fernandes (2009). culori multiplies them with
|
|
67
|
+
* gamma-encoded sRGB, but the model describes light reaching the cones, which adds up linearly. The R
|
|
68
|
+
* `colorspace` package, which culori took the matrices from, fixed the same issue in version 2.1-0.
|
|
69
|
+
* So this function hands culori's filter linear-light channels and re-encodes the result.
|
|
70
|
+
* @see {@link https://doi.org/10.1109/TVCG.2009.113}
|
|
71
|
+
* @see {@link https://www.zeileis.org/news/simulate_cvd/}
|
|
72
|
+
*
|
|
73
|
+
* @param severity from 0 (typical vision) to 1 (dichromacy, the default). Values in between approximate
|
|
74
|
+
* anomalous trichromacy. culori rounds them to the nearest 0.1, the steps that Machado et al. published.
|
|
75
|
+
*/
|
|
76
|
+
export function simulateVision(color, vision, severity = 1) {
|
|
77
|
+
const rgb = parseColor(color);
|
|
78
|
+
if (vision === 'normal') {
|
|
79
|
+
return rgb;
|
|
80
|
+
}
|
|
81
|
+
const linear = toLrgb(rgb);
|
|
82
|
+
// Labelled as 'rgb' on purpose: culori's filter then applies the matrix to these channels as they are.
|
|
83
|
+
const filtered = FILTERS[vision](severity)({
|
|
84
|
+
mode: 'rgb',
|
|
85
|
+
r: linear.r,
|
|
86
|
+
g: linear.g,
|
|
87
|
+
b: linear.b,
|
|
88
|
+
});
|
|
89
|
+
return clampRgb(toRgb({ mode: 'lrgb', r: filtered.r, g: filtered.g, b: filtered.b }));
|
|
90
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ThemeReport } from './analyze.js';
|
|
2
|
+
/**
|
|
3
|
+
* One readable line per failed check. Checks without a threshold never fail.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* expect(themeFailures(analyzeTheme(myTheme))).toEqual([]);
|
|
7
|
+
*/
|
|
8
|
+
export declare function themeFailures(report: ThemeReport): string[];
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { CRITERIA } from './standards.js';
|
|
2
|
+
/** Two decimals, or more when two would round a failing value up to the threshold. */
|
|
3
|
+
function format(value, threshold) {
|
|
4
|
+
let digits = 2;
|
|
5
|
+
while (threshold != null && digits < 6 && Number(value.toFixed(digits)) >= threshold) {
|
|
6
|
+
digits++;
|
|
7
|
+
}
|
|
8
|
+
return value.toFixed(digits);
|
|
9
|
+
}
|
|
10
|
+
/** The suggested color as a sentence to append to a failure, or nothing when there is no fix. */
|
|
11
|
+
function describeFix({ fix }) {
|
|
12
|
+
if (fix == null) {
|
|
13
|
+
return '';
|
|
14
|
+
}
|
|
15
|
+
const what = fix.target === 'text' ? 'label color' : `series ${(fix.series ?? 0) + 1}`;
|
|
16
|
+
return `. Try ${what} ${fix.to} instead of ${fix.from}`;
|
|
17
|
+
}
|
|
18
|
+
/** One failure as a line: the check, where, the colors, the measured value against its threshold, and the standard. */
|
|
19
|
+
function describeFailure(result) {
|
|
20
|
+
const who = result.series.length === 0 ? 'text' : result.series.map((i) => `series ${i + 1}`).join(' vs ');
|
|
21
|
+
const subject = result.mark == null ? who : `${who} ${result.mark}`;
|
|
22
|
+
const measured = result.check === 'seriesVsSeries'
|
|
23
|
+
? `ΔE00 ${format(result.value, result.threshold)} < ${result.threshold}`
|
|
24
|
+
: `${format(result.value, result.threshold)}:1 < ${result.threshold}:1`;
|
|
25
|
+
return (`${result.check} [${result.background}, ${result.vision}] ${subject} ` +
|
|
26
|
+
`(${result.colors[0]} / ${result.colors[1]}): ${measured}, ${CRITERIA[result.criterion].title}` +
|
|
27
|
+
describeFix(result));
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* One readable line per failed check. Checks without a threshold never fail.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* expect(themeFailures(analyzeTheme(myTheme))).toEqual([]);
|
|
34
|
+
*/
|
|
35
|
+
export function themeFailures(report) {
|
|
36
|
+
return report.checks.filter((result) => result.passes === false).map(describeFailure);
|
|
37
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { colorDifference, composite, contrastRatio, parseColor, simulateVision, toHex, VISIONS, } from './color.js';
|
|
2
|
+
export type { ColorInput, Vision } from './color.js';
|
|
3
|
+
export { analyzeTheme } from './analyze.js';
|
|
4
|
+
export type { CheckId, CheckResult, Fix, Mark, ThemeCheckOptions, ThemeReport, ThemeSeries, Thresholds, } from './analyze.js';
|
|
5
|
+
export { themeFailures } from './failures.js';
|
|
6
|
+
export { nearestPassingColor } from './suggest.js';
|
|
7
|
+
export { CRITERIA, WCAG_CONTRAST } from './standards.js';
|
|
8
|
+
export type { Criterion, CriterionId } from './standards.js';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { colorDifference, composite, contrastRatio, parseColor, simulateVision, toHex, VISIONS, } from './color.js';
|
|
2
|
+
export { analyzeTheme } from './analyze.js';
|
|
3
|
+
export { themeFailures } from './failures.js';
|
|
4
|
+
export { nearestPassingColor } from './suggest.js';
|
|
5
|
+
export { CRITERIA, WCAG_CONTRAST } from './standards.js';
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The standards behind each check, with links, so that every threshold in a report can be traced back
|
|
3
|
+
* to the text that defines it.
|
|
4
|
+
*/
|
|
5
|
+
export type CriterionId = 'wcag-1.4.3' | 'wcag-1.4.6' | 'wcag-1.4.11' | 'wcag-1.4.1' | 'ciede2000';
|
|
6
|
+
export type Criterion = {
|
|
7
|
+
id: CriterionId;
|
|
8
|
+
title: string;
|
|
9
|
+
url: string;
|
|
10
|
+
};
|
|
11
|
+
export declare const CRITERIA: Readonly<Record<CriterionId, Criterion>>;
|
|
12
|
+
/**
|
|
13
|
+
* Contrast ratios that WCAG 2.2 defines. Pick the one that matches your text size and target level.
|
|
14
|
+
* "Large" text is at least 18pt, or 14pt bold.
|
|
15
|
+
* @see {@link https://www.w3.org/TR/WCAG22/#dfn-large-scale}
|
|
16
|
+
*/
|
|
17
|
+
export declare const WCAG_CONTRAST: {
|
|
18
|
+
/** SC 1.4.3, level AA, normal text */
|
|
19
|
+
readonly text: 4.5;
|
|
20
|
+
/** SC 1.4.3, level AA, large text */
|
|
21
|
+
readonly largeText: 3;
|
|
22
|
+
/** SC 1.4.6, level AAA, normal text */
|
|
23
|
+
readonly enhancedText: 7;
|
|
24
|
+
/** SC 1.4.6, level AAA, large text */
|
|
25
|
+
readonly enhancedLargeText: 4.5;
|
|
26
|
+
/** SC 1.4.11, level AA, graphical objects */
|
|
27
|
+
readonly nonText: 3;
|
|
28
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The standards behind each check, with links, so that every threshold in a report can be traced back
|
|
3
|
+
* to the text that defines it.
|
|
4
|
+
*/
|
|
5
|
+
export const CRITERIA = {
|
|
6
|
+
'wcag-1.4.1': {
|
|
7
|
+
id: 'wcag-1.4.1',
|
|
8
|
+
title: 'WCAG 2.2 Success Criterion 1.4.1 Use of Color (Level A)',
|
|
9
|
+
url: 'https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html',
|
|
10
|
+
},
|
|
11
|
+
'wcag-1.4.3': {
|
|
12
|
+
id: 'wcag-1.4.3',
|
|
13
|
+
title: 'WCAG 2.2 Success Criterion 1.4.3 Contrast (Minimum) (Level AA)',
|
|
14
|
+
url: 'https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html',
|
|
15
|
+
},
|
|
16
|
+
'wcag-1.4.6': {
|
|
17
|
+
id: 'wcag-1.4.6',
|
|
18
|
+
title: 'WCAG 2.2 Success Criterion 1.4.6 Contrast (Enhanced) (Level AAA)',
|
|
19
|
+
url: 'https://www.w3.org/WAI/WCAG22/Understanding/contrast-enhanced.html',
|
|
20
|
+
},
|
|
21
|
+
'wcag-1.4.11': {
|
|
22
|
+
id: 'wcag-1.4.11',
|
|
23
|
+
title: 'WCAG 2.2 Success Criterion 1.4.11 Non-text Contrast (Level AA)',
|
|
24
|
+
url: 'https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html',
|
|
25
|
+
},
|
|
26
|
+
ciede2000: {
|
|
27
|
+
id: 'ciede2000',
|
|
28
|
+
title: 'CIEDE2000 color difference (ISO/CIE 11664-6), no pass or fail threshold defined',
|
|
29
|
+
url: 'https://hajim.rochester.edu/ece/sites/gsharma/ciede2000/',
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Contrast ratios that WCAG 2.2 defines. Pick the one that matches your text size and target level.
|
|
34
|
+
* "Large" text is at least 18pt, or 14pt bold.
|
|
35
|
+
* @see {@link https://www.w3.org/TR/WCAG22/#dfn-large-scale}
|
|
36
|
+
*/
|
|
37
|
+
export const WCAG_CONTRAST = {
|
|
38
|
+
/** SC 1.4.3, level AA, normal text */
|
|
39
|
+
text: 4.5,
|
|
40
|
+
/** SC 1.4.3, level AA, large text */
|
|
41
|
+
largeText: 3,
|
|
42
|
+
/** SC 1.4.6, level AAA, normal text */
|
|
43
|
+
enhancedText: 7,
|
|
44
|
+
/** SC 1.4.6, level AAA, large text */
|
|
45
|
+
enhancedLargeText: 4.5,
|
|
46
|
+
/** SC 1.4.11, level AA, graphical objects */
|
|
47
|
+
nonText: 3,
|
|
48
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The color closest in lightness to `color` that `passes`, keeping its hue and as much of its chroma as the
|
|
3
|
+
* sRGB gamut allows. It tries lighter and darker one step at a time and returns the first that passes,
|
|
4
|
+
* or `null` when no lightness works, for example when the hue itself is the problem.
|
|
5
|
+
*
|
|
6
|
+
* The search moves along OKLCH lightness, so the hue stays the same and only lightness (and, at the gamut
|
|
7
|
+
* edge, chroma) changes.
|
|
8
|
+
* @see {@link https://www.w3.org/TR/css-color-4/#ok-lab}
|
|
9
|
+
*/
|
|
10
|
+
export declare function nearestPassingColor(color: string, passes: (hex: string) => boolean): string | null;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { clampChroma, converter, formatHex } from 'culori';
|
|
2
|
+
import { parseColor } from './color.js';
|
|
3
|
+
const toOklch = converter('oklch');
|
|
4
|
+
/** How far, in OKLCH lightness (0 to 1), one search step moves. */
|
|
5
|
+
const STEP = 0.002;
|
|
6
|
+
/**
|
|
7
|
+
* The color closest in lightness to `color` that `passes`, keeping its hue and as much of its chroma as the
|
|
8
|
+
* sRGB gamut allows. It tries lighter and darker one step at a time and returns the first that passes,
|
|
9
|
+
* or `null` when no lightness works, for example when the hue itself is the problem.
|
|
10
|
+
*
|
|
11
|
+
* The search moves along OKLCH lightness, so the hue stays the same and only lightness (and, at the gamut
|
|
12
|
+
* edge, chroma) changes.
|
|
13
|
+
* @see {@link https://www.w3.org/TR/css-color-4/#ok-lab}
|
|
14
|
+
*/
|
|
15
|
+
export function nearestPassingColor(color, passes) {
|
|
16
|
+
const start = toOklch(parseColor(color));
|
|
17
|
+
for (let delta = STEP; delta <= 1; delta += STEP) {
|
|
18
|
+
for (const l of [start.l - delta, start.l + delta]) {
|
|
19
|
+
if (l < 0 || l > 1) {
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const candidate = formatHex(clampChroma({ ...start, l }, 'oklch'));
|
|
23
|
+
if (passes(candidate)) {
|
|
24
|
+
return candidate;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
package/package.json
CHANGED
|
@@ -4,10 +4,21 @@
|
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
6
|
"type": "module",
|
|
7
|
-
"version": "0.0.
|
|
7
|
+
"version": "0.0.20",
|
|
8
8
|
"description": "Devtools and helper functions for Recharts",
|
|
9
9
|
"main": "dist/index.js",
|
|
10
10
|
"types": "dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"default": "./dist/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./theme": {
|
|
17
|
+
"types": "./dist/theme/index.d.ts",
|
|
18
|
+
"default": "./dist/theme/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./package.json": "./package.json"
|
|
21
|
+
},
|
|
11
22
|
"files": [
|
|
12
23
|
"dist"
|
|
13
24
|
],
|
|
@@ -29,25 +40,41 @@
|
|
|
29
40
|
"author": "Recharts Group",
|
|
30
41
|
"license": "MIT",
|
|
31
42
|
"devDependencies": {
|
|
43
|
+
"@eslint/js": "^10.0.1",
|
|
32
44
|
"@testing-library/react": "^16.3.2",
|
|
45
|
+
"@types/culori": "^4.0.1",
|
|
33
46
|
"@types/node": "^26.1.0",
|
|
34
47
|
"@types/react": "^18.0.0",
|
|
35
48
|
"@types/react-dom": "^18.0.0",
|
|
36
|
-
"eslint": "^
|
|
37
|
-
"eslint-plugin-import": "^
|
|
49
|
+
"eslint": "^10.13.0",
|
|
50
|
+
"eslint-plugin-import-x": "^4.17.1",
|
|
38
51
|
"globals": "^17.6.0",
|
|
39
|
-
"jsdom": "^
|
|
52
|
+
"jsdom": "^31.0.0",
|
|
40
53
|
"prettier": "^3.0.0",
|
|
41
54
|
"react": "^19.0.0",
|
|
42
55
|
"react-dom": "^19.0.0",
|
|
43
|
-
"recharts": "^3.
|
|
56
|
+
"recharts": "^3.11.0",
|
|
44
57
|
"typescript": "^5.0.0",
|
|
45
58
|
"typescript-eslint": "^8.0.0",
|
|
46
|
-
"vitest": "^
|
|
59
|
+
"vitest": "^5.0.2"
|
|
47
60
|
},
|
|
48
61
|
"peerDependencies": {
|
|
49
62
|
"react": "^18.0.0 || ^19.0.0",
|
|
50
63
|
"react-dom": "^18.0.0 || ^19.0.0",
|
|
51
|
-
"recharts": "3.9.0"
|
|
64
|
+
"recharts": "^3.9.0"
|
|
65
|
+
},
|
|
66
|
+
"peerDependenciesMeta": {
|
|
67
|
+
"react": {
|
|
68
|
+
"optional": true
|
|
69
|
+
},
|
|
70
|
+
"react-dom": {
|
|
71
|
+
"optional": true
|
|
72
|
+
},
|
|
73
|
+
"recharts": {
|
|
74
|
+
"optional": true
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
"dependencies": {
|
|
78
|
+
"culori": "^4.0.2"
|
|
52
79
|
}
|
|
53
80
|
}
|