forked from nasa/openmct
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtickUtils.js
More file actions
330 lines (281 loc) · 8.7 KB
/
Copy pathtickUtils.js
File metadata and controls
330 lines (281 loc) · 8.7 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import { antisymlog, symlog } from './mathUtils.js';
const e10 = Math.sqrt(50);
const e5 = Math.sqrt(10);
const e2 = Math.sqrt(2);
// A complete list of time units and their duration in milliseconds - UTC
const TIME_UNITS_UTC = [
{ unit: 'millisecond', duration: 1 },
{ unit: 'second', duration: 1000 },
{ unit: 'minute', duration: 1000 * 60 },
{ unit: 'hour', duration: 1000 * 60 * 60 },
{ unit: 'day', duration: 1000 * 60 * 60 * 24 },
{ unit: 'week', duration: 1000 * 60 * 60 * 24 * 7 },
{ unit: 'month', duration: 1000 * 60 * 60 * 24 * 30.4375 }, // Average month
{ unit: 'year', duration: 1000 * 60 * 60 * 24 * 365.25 } // Average year
];
/**
* Nicely formatted tick steps from d3-array.
*/
function tickStep(start, stop, count) {
const step0 = Math.abs(stop - start) / Math.max(1, count);
let step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10));
const error = step0 / step1;
if (error >= e10) {
step1 *= 10;
} else if (error >= e5) {
step1 *= 5;
} else if (error >= e2) {
step1 *= 2;
}
return stop < start ? -step1 : step1;
}
/**
* tickStep for time units - allows for snapping to 15/30 minutes and 6/12 hours, which are common intervals.
*/
function timeTickStep(start, stop, count, unitName) {
const step0 = Math.abs(stop - start) / Math.max(1, count);
let step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10));
const error = step0 / step1;
// For minutes and seconds, allow snapping to 15 and 30
if (unitName === 'minute' || unitName === 'second') {
// Snap to 1 hour/minute
if (error >= 45) {
return 60;
}
// Snap to 30s/30m
if (error >= 22.5) {
return 30;
}
// Snap to 15s/15m
if (error >= 12.5) {
return 15;
}
}
// For hours, use to 6 and 12
if (unitName === 'hour') {
// Snap to 1 day
if (error >= 18) {
return 24;
}
if (error >= 9) {
return 12;
}
if (error >= 4.5) {
return 6;
}
}
// Fallback to standard tickStep that already snaps to 1, 2, 5, 10
if (error >= 7.5) {
step1 *= 10;
} else if (error >= 3.0) {
step1 *= 5;
} else if (error >= 1.5) {
step1 *= 2;
}
return stop < start ? -step1 : step1;
}
/**
* Generate time ticks based on a start and stop time, and a desired count of ticks calculated proactively from canvas size
* @param start beginning timestamp in Ms
* @param stop ending timestamp in Ms
* @param count desired number of ticks
* @returns {*[]} Array of timestamps in Ms
*/
export function getTimeTicks(start, stop, count) {
const duration = stop - start;
let bestUnit = TIME_UNITS_UTC[0];
// Find the unit where the duration divided by unit size is closest to our target count.
for (const unit of TIME_UNITS_UTC) {
const ticksForUnit = duration / unit.duration;
if (ticksForUnit <= count) {
break;
}
bestUnit = unit;
}
// Normalize the range to the selected unit to find a "nice" step size
const startInUnits = start / bestUnit.duration;
const stopInUnits = stop / bestUnit.duration;
// Use specialized time stepping for seconds/minutes/hours
const bestStepSize = Math.abs(timeTickStep(startInUnits, stopInUnits, count, bestUnit.unit));
if (bestUnit.unit === 'month' || bestUnit.unit === 'year') {
return generateMonthYearTicks(start, stop, bestUnit.unit, bestStepSize);
} else {
return generateFixedIntervalTicks(start, stop, bestUnit.duration * bestStepSize);
}
}
// Helper for variable-duration units (months, years)
/**
* Generate ticks for month/year intervals - these are variable due to leap years etc.
* @param start beginning timestamp in Ms
* @param stop ending timestamp in Ms
* @param unit 'month' or 'year'
* @param stepSize number of months/years to step
* @returns {*[]} Array of timestamps in Ms
*/
function generateMonthYearTicks(start, stop, unit, stepSize) {
const resultingTicks = [];
let currentDate = new Date(start);
// Use UTC to avoid DST issues.
// Set to the beginning of the interval (e.g., beginning of the month/year)
if (unit === 'month') {
// currentDate.setDate(1);
currentDate.setUTCDate(1);
currentDate.setUTCHours(0, 0, 0, 0);
} else if (unit === 'year') {
// currentDate.setMonth(0, 1);
currentDate.setUTCMonth(0, 1);
currentDate.setUTCHours(0, 0, 0, 0);
}
while (currentDate.getTime() <= stop) {
resultingTicks.push(currentDate.getTime());
if (unit === 'month') {
// currentDate.setMonth(currentDate.getMonth() + stepSize);
currentDate.setUTCMonth(currentDate.getUTCMonth() + stepSize);
} else {
// unit is 'year'
// currentDate.setFullYear(currentDate.getFullYear() + stepSize);
currentDate.setUTCFullYear(currentDate.getUTCFullYear() + stepSize);
}
}
return resultingTicks;
}
// Helper for fixed-duration units (seconds, days)
/**
* Generate ticks for fixed-duration intervals (seconds, minutes, hours, etc.)
* @param start beginning timestamp in Ms
* @param stop ending timestamp in Ms
* @param interval duration of each tick in Ms
* @returns {*[]} Array of timestamps in Ms
*/
function generateFixedIntervalTicks(start, stop, interval) {
const fixedIntervalTicks = [];
const firstTick = Math.ceil(start / interval) * interval;
for (let i = firstTick; i <= stop; i += interval) {
fixedIntervalTicks.push(i);
}
return fixedIntervalTicks;
}
/**
* Find the precision (number of decimals) of a step. Used to round
* ticks to precise values.
*/
function getPrecision(step) {
const exponential = step.toExponential();
const i = exponential.indexOf('e');
if (i === -1) {
return 0;
}
let precision = Math.max(0, -Number(exponential.slice(i + 1)));
if (precision > 20) {
precision = 20;
}
return precision;
}
export function getLogTicks(start, stop, mainTickCount = 8, secondaryTickCount = 6) {
// log()'ed values
const mainLogTicks = ticks(start, stop, mainTickCount);
// original values
const mainTicks = mainLogTicks.map((n) => antisymlog(n, 10));
const result = [];
let i = 0;
for (const logTick of mainLogTicks) {
result.push(logTick);
if (i === mainLogTicks.length - 1) {
break;
}
const tick = mainTicks[i];
const nextTick = mainTicks[i + 1];
const rangeBetweenMainTicks = nextTick - tick;
const secondaryLogTicks = ticks(
tick + rangeBetweenMainTicks / (secondaryTickCount + 1),
nextTick - rangeBetweenMainTicks / (secondaryTickCount + 1),
Math.max(1, secondaryTickCount - 2)
).map((n) => symlog(n, 10));
result.push(...secondaryLogTicks);
i++;
}
return result;
}
/**
* Linear tick generation from d3-array.
*/
export function ticks(start, stop, count) {
if (count < 1) {
return [];
}
const step = tickStep(start, stop, count);
const precision = getPrecision(step);
return _.range(
Math.ceil(start / step) * step,
Math.floor(stop / step) * step + step / 2, // inclusive
step
).map(function round(tick) {
return Number(tick.toFixed(precision));
});
}
export function commonPrefix(a, b) {
const maxLen = Math.min(a.length, b?.length);
let breakpoint = 0;
for (let i = 0; i < maxLen; i++) {
if (a[i] !== b[i]) {
break;
}
if (a[i] === ' ') {
breakpoint = i + 1;
}
}
return a.slice(0, breakpoint);
}
export function commonSuffix(a, b) {
const maxLen = Math.min(a.length, b?.length);
let breakpoint = 0;
for (let i = 0; i <= maxLen; i++) {
if (a[a.length - i] !== b[b.length - i]) {
break;
}
if ('. '.indexOf(a[a.length - i]) !== -1) {
breakpoint = i;
}
}
return a.slice(a.length - breakpoint);
}
export function getFormattedTicks(newTicks, format) {
newTicks = newTicks.map(function (tickValue) {
return {
value: tickValue,
text: format(tickValue)
};
});
if (newTicks.length && typeof newTicks[0].text === 'string') {
const tickText = newTicks.map(function (t) {
return t.text;
});
const prefix = tickText.reduce(commonPrefix);
const suffix = tickText.reduce(commonSuffix);
newTicks.forEach(function (t) {
t.fullText = t.text;
if (typeof t.text === 'string') {
if (newTicks.length > 1) {
if (suffix.length) {
t.text = t.text.slice(prefix.length, -suffix.length);
} else {
t.text = t.text.slice(prefix.length);
}
}
}
});
}
return newTicks;
}
/**
* Proactively measures text width using a canvas context.
*/
let measurementContext;
export function measureTextWidth(text, font = '12px "Helvetica", sans-serif') {
if (!measurementContext) {
const canvas = document.createElement('canvas');
measurementContext = canvas.getContext('2d');
}
measurementContext.font = font;
return measurementContext.measureText(text).width;
}