-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
CartesianUtils.ts
282 lines (243 loc) · 9.11 KB
/
CartesianUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import mapValues from 'lodash/mapValues';
import every from 'lodash/every';
import { getTicksOfScale, parseScale, checkDomainOfScale, getBandSizeOfAxis } from './ChartUtils';
import { findChildByType } from './ReactUtils';
import { Coordinate, AxisType, Size } from './types';
import { getPercentValue } from './DataUtils';
import { Bar } from '../cartesian/Bar';
import { StepRatioControl } from './scale/getNiceTickValues';
/**
* Calculate the scale function, position, width, height of axes
* @param {Object} props Latest props
* @param {Object} axisMap The configuration of axes
* @param {Object} offset The offset of main part in the svg element
* @param {String} axisType The type of axes, x-axis or y-axis
* @param {String} chartName The name of chart
* @param {StepRatioControl} stepRatioControl The value to control the step of y domain
* @return {Object} Configuration
*/
export const formatAxisMap = (
props: any,
axisMap: any,
offset: any,
axisType: AxisType,
chartName: string,
stepRatioControl: StepRatioControl = 0.05,
) => {
const { width, height, layout, children } = props;
const ids = Object.keys(axisMap);
const steps: Record<string, any> = {
left: offset.left,
leftMirror: offset.left,
right: width - offset.right,
rightMirror: width - offset.right,
top: offset.top,
topMirror: offset.top,
bottom: height - offset.bottom,
bottomMirror: height - offset.bottom,
};
const hasBar = !!findChildByType(children, Bar);
return ids.reduce((result, id) => {
const axis = axisMap[id];
const { orientation, domain, padding = {}, mirror, reversed } = axis;
const offsetKey = `${orientation}${mirror ? 'Mirror' : ''}`;
let calculatedPadding, range, x, y, needSpace;
if (axis.type === 'number' && (axis.padding === 'gap' || axis.padding === 'no-gap')) {
const diff = domain[1] - domain[0];
let smallestDistanceBetweenValues = Infinity;
const sortedValues = axis.categoricalDomain.sort();
sortedValues.forEach((value: number, index: number) => {
if (index > 0) {
smallestDistanceBetweenValues = Math.min(
(value || 0) - (sortedValues[index - 1] || 0),
smallestDistanceBetweenValues,
);
}
});
if (Number.isFinite(smallestDistanceBetweenValues)) {
const smallestDistanceInPercent = smallestDistanceBetweenValues / diff;
const rangeWidth = axis.layout === 'vertical' ? offset.height : offset.width;
if (axis.padding === 'gap') {
calculatedPadding = (smallestDistanceInPercent * rangeWidth) / 2;
}
if (axis.padding === 'no-gap') {
const gap = getPercentValue(props.barCategoryGap, smallestDistanceInPercent * rangeWidth);
const halfBand = (smallestDistanceInPercent * rangeWidth) / 2;
calculatedPadding = halfBand - gap - ((halfBand - gap) / rangeWidth) * gap;
}
}
}
if (axisType === 'xAxis') {
range = [
offset.left + (padding.left || 0) + (calculatedPadding || 0),
offset.left + offset.width - (padding.right || 0) - (calculatedPadding || 0),
];
} else if (axisType === 'yAxis') {
range =
layout === 'horizontal'
? [offset.top + offset.height - (padding.bottom || 0), offset.top + (padding.top || 0)]
: [
offset.top + (padding.top || 0) + (calculatedPadding || 0),
offset.top + offset.height - (padding.bottom || 0) - (calculatedPadding || 0),
];
} else {
({ range } = axis);
}
if (reversed) {
range = [range[1], range[0]];
}
const { scale, realScaleType } = parseScale(axis, chartName, hasBar);
scale.domain(domain).range(range);
checkDomainOfScale(scale);
const ticks = getTicksOfScale(scale, { ...axis, realScaleType, stepRatioControl });
if (axisType === 'xAxis') {
needSpace = (orientation === 'top' && !mirror) || (orientation === 'bottom' && mirror);
x = offset.left;
y = steps[offsetKey] - needSpace * axis.height;
} else if (axisType === 'yAxis') {
needSpace = (orientation === 'left' && !mirror) || (orientation === 'right' && mirror);
x = steps[offsetKey] - needSpace * axis.width;
y = offset.top;
}
const finalAxis = {
...axis,
...ticks,
realScaleType,
x,
y,
scale,
width: axisType === 'xAxis' ? offset.width : axis.width,
height: axisType === 'yAxis' ? offset.height : axis.height,
};
finalAxis.bandSize = getBandSizeOfAxis(finalAxis, ticks as any);
if (!axis.hide && axisType === 'xAxis') {
steps[offsetKey] += (needSpace ? -1 : 1) * finalAxis.height;
} else if (!axis.hide) {
steps[offsetKey] += (needSpace ? -1 : 1) * finalAxis.width;
}
return { ...result, [id]: finalAxis };
}, {});
};
export const rectWithPoints = ({ x: x1, y: y1 }: Coordinate, { x: x2, y: y2 }: Coordinate) => ({
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1),
});
/**
* Compute the x, y, width, and height of a box from two reference points.
* @param {Object} coords x1, x2, y1, and y2
* @return {Object} object
*/
export const rectWithCoords = ({ x1, y1, x2, y2 }: { x1: number; y1: number; x2: number; y2: number }) =>
rectWithPoints({ x: x1, y: y1 }, { x: x2, y: y2 });
export class ScaleHelper {
static EPS = 1e-4;
private scale: any;
static create(obj: any) {
return new ScaleHelper(obj);
}
constructor(scale: any) {
this.scale = scale;
}
get domain() {
return this.scale.domain;
}
get range() {
return this.scale.range;
}
get rangeMin() {
return this.range()[0];
}
get rangeMax() {
return this.range()[1];
}
get bandwidth() {
return this.scale.bandwidth;
}
apply(value: any, { bandAware, position }: { bandAware?: boolean; position?: any } = {}) {
if (value === undefined) {
return undefined;
}
if (position) {
switch (position) {
case 'start': {
return this.scale(value);
}
case 'middle': {
const offset = this.bandwidth ? this.bandwidth() / 2 : 0;
return this.scale(value) + offset;
}
case 'end': {
const offset = this.bandwidth ? this.bandwidth() : 0;
return this.scale(value) + offset;
}
default: {
return this.scale(value);
}
}
}
if (bandAware) {
const offset = this.bandwidth ? this.bandwidth() / 2 : 0;
return this.scale(value) + offset;
}
return this.scale(value);
}
isInRange(value: number) {
const range = this.range();
const first = range[0];
const last = range[range.length - 1];
return first <= last ? value >= first && value <= last : value >= last && value <= first;
}
}
type ScaleResult<T> = {
[P in keyof T]: number;
};
type Scales<T> = {
[P in keyof T]: ScaleHelper;
};
type ScalesApply<T> = (coord: { [P in keyof T]: any }, options: any) => ScaleResult<T>;
type ScalesIsInRange<T> = (coord: { [P in keyof T]: any }) => boolean;
type LabeledScales<T> = Scales<T> & { apply: ScalesApply<T> } & { isInRange: ScalesIsInRange<T> };
export const createLabeledScales = (options: Record<string, any>): LabeledScales<Record<string, any>> => {
const scales: Scales<Record<string, any>> = Object.keys(options).reduce(
(res, key: string) => ({
...res,
[key]: ScaleHelper.create(options[key]),
}),
{},
);
return {
...scales,
apply(coord: any, { bandAware, position }: any = {}) {
return mapValues(coord, (value, label) => scales[label].apply(value, { bandAware, position }));
},
isInRange(coord: any) {
return every(coord, (value, label) => scales[label].isInRange(value));
},
} as LabeledScales<Record<string, any>>;
};
/** Normalizes the angle so that 0 <= angle < 180.
* @param {number} angle Angle in degrees.
* @return {number} the normalized angle with a value of at least 0 and never greater or equal to 180. */
export function normalizeAngle(angle: number) {
return ((angle % 180) + 180) % 180;
}
/** Calculates the width of the largest horizontal line that fits inside a rectangle that is displayed at an angle.
* @param {Object} size Width and height of the text in a horizontal position.
* @param {number} angle Angle in degrees in which the text is displayed.
* @return {number} The width of the largest horizontal line that fits inside a rectangle that is displayed at an angle.
*/
export const getAngledRectangleWidth = ({ width, height }: Size, angle: number | undefined = 0) => {
// Ensure angle is >= 0 && < 180
const normalizedAngle = normalizeAngle(angle);
const angleRadians = (normalizedAngle * Math.PI) / 180;
/* Depending on the height and width of the rectangle, we may need to use different formulas to calculate the angled
* width. This threshold defines when each formula should kick in. */
const angleThreshold = Math.atan(height / width);
const angledWidth =
angleRadians > angleThreshold && angleRadians < Math.PI - angleThreshold
? height / Math.sin(angleRadians)
: width / Math.cos(angleRadians);
return Math.abs(angledWidth);
};