forked from deephaven/web-client-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataBarCellRenderer.ts
More file actions
560 lines (513 loc) · 17.6 KB
/
DataBarCellRenderer.ts
File metadata and controls
560 lines (513 loc) · 17.6 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/* eslint-disable class-methods-use-this */
import { getOrThrow } from '@deephaven/utils';
import CellRenderer from './CellRenderer';
import { isExpandableGridModel } from './ExpandableGridModel';
import { isDataBarGridModel } from './DataBarGridModel';
import {
type ModelIndex,
type VisibleIndex,
type VisibleToModelMap,
} from './GridMetrics';
import GridColorUtils from './GridColorUtils';
import GridUtils from './GridUtils';
import memoizeClear from './memoizeClear';
import { type GridRenderState } from './GridRendererTypes';
import type GridModel from './GridModel';
interface DataBarRenderMetrics {
/** The total width the entire bar from the min to max value can take up (rightmostPosition - leftmostPosition) */
maxWidth: number;
/** The x coordinate of the bar (the left) */
x: number;
/** The y coordinate of the bar (the top) */
y: number;
/** The position of the zero line */
zeroPosition: number;
/** The position of the leftmost point */
leftmostPosition: number;
/** The position of the rightmost point */
rightmostPosition: number;
/** The range of values (e.g. max of 100 and min of -50 means range of 150) */
totalValueRange: number;
/** The width of the databar */
dataBarWidth: number;
/** The x coordinates of the markers (the left) */
markerXs: number[];
}
class DataBarCellRenderer extends CellRenderer {
static getGradient = memoizeClear(
(width: number, colors: string[]): CanvasGradient => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (ctx == null) {
throw new Error('Failed to create canvas context');
}
if (Number.isNaN(width)) {
return ctx.createLinearGradient(0, 0, 0, 0);
}
const gradient = ctx.createLinearGradient(0, 0, width, 0);
const oklabColors = colors.map(color =>
GridColorUtils.linearSRGBToOklab(GridColorUtils.hexToRgb(color))
);
for (let i = 0; i < width; i += 1) {
const colorStop = i / width;
const colorChangeInterval = 1 / (colors.length - 1);
const leftColorIndex = Math.floor(colorStop / colorChangeInterval);
const color = GridColorUtils.lerpColor(
oklabColors[leftColorIndex],
oklabColors[leftColorIndex + 1],
(colorStop % colorChangeInterval) / colorChangeInterval
);
gradient.addColorStop(
i / width,
GridColorUtils.rgbToHex(GridColorUtils.OklabToLinearSRGB(color))
);
}
return gradient;
},
{
max: 1000,
primitive: true, // Stringify the arguments for memoization. Lets the color arrays be different arrays in memory, but still cache hit
}
);
drawCellContent(
context: CanvasRenderingContext2D,
state: GridRenderState,
column: VisibleIndex,
row: VisibleIndex
): void {
const { metrics, model, theme } = state;
if (!isDataBarGridModel(model)) {
return;
}
const {
modelColumns,
modelRows,
allRowHeights,
allRowYs,
firstColumn,
fontWidthsLower,
fontWidthsUpper,
} = metrics;
const isFirstColumn = column === firstColumn;
const rowHeight = getOrThrow(allRowHeights, row);
const modelRow = getOrThrow(modelRows, row);
const modelColumn = getOrThrow(modelColumns, column);
const rowY = getOrThrow(allRowYs, row);
const textAlign = model.textAlignForCell(modelColumn, modelRow);
const text = model.textForCell(modelColumn, modelRow);
const {
x: textX,
y: textY,
width: textWidth,
} = GridUtils.getTextRenderMetrics(state, column, row);
const fontWidthLower = fontWidthsLower.get(context.font);
const fontWidthUpper = fontWidthsUpper.get(context.font);
const truncationChar = model.truncationCharForCell(modelColumn, modelRow);
const truncatedText = this.getCachedTruncatedString(
context,
text,
textWidth,
fontWidthLower,
fontWidthUpper,
truncationChar
);
const {
columnMin,
columnMax,
axis,
color: dataBarColor,
valuePlacement,
opacity,
markers,
direction,
value,
} = model.dataBarOptionsForCell(modelColumn, modelRow, theme);
const hasGradient = Array.isArray(dataBarColor) && dataBarColor.length > 1;
if (columnMin == null || columnMax == null) {
return;
}
const {
maxWidth,
x: dataBarX,
y: dataBarY,
zeroPosition,
leftmostPosition,
markerXs,
totalValueRange,
dataBarWidth,
} = this.getDataBarRenderMetrics(context, state, column, row);
context.save();
context.textAlign = textAlign;
// Use explicit format color if set.
// Otherwise, fall back to the databar color for text.
const formatColor = model.formatColorForCell(modelColumn, modelRow);
if (formatColor != null) {
context.fillStyle = formatColor;
} else if (hasGradient) {
const color =
value >= 0 ? dataBarColor[dataBarColor.length - 1] : dataBarColor[0];
context.fillStyle = color;
} else {
context.fillStyle = Array.isArray(dataBarColor)
? dataBarColor[0]
: dataBarColor;
}
context.textBaseline = 'middle';
context.font = theme.font;
if (valuePlacement !== 'hide') {
context.fillText(truncatedText, textX, textY);
}
const hasRowDividers = theme.gridRowColor != null;
const yOffset = hasRowDividers ? 2 : 1;
context.save();
context.beginPath();
context.roundRect(
dataBarX,
rowY + yOffset, // yOffset includes 1px for top padding
dataBarWidth,
rowHeight - 1 - yOffset, // 1px for bottom padding
1
);
context.clip();
context.globalAlpha = opacity;
// Draw bar
if (hasGradient) {
// Draw gradient bar
let gradientWidth = 0;
let gradientX = 0;
context.save();
// Translate the context so its origin is at the start of the gradient
// and increasing x value moves towards the end of the gradient.
// For RTL, scale x by -1 to flip across the x-axis
if (value < 0) {
if (direction === 'LTR') {
gradientWidth = Math.round(
(Math.abs(columnMin) / totalValueRange) * maxWidth
);
gradientX = Math.round(leftmostPosition);
context.translate(gradientX, 0);
} else if (direction === 'RTL') {
gradientWidth = Math.round(
maxWidth - (Math.abs(columnMax) / totalValueRange) * maxWidth
);
gradientX = Math.round(zeroPosition);
context.translate(gradientX + gradientWidth, 0);
context.scale(-1, 1);
}
} else if (direction === 'LTR') {
// Value is greater than or equal to 0
gradientWidth =
Math.round(
maxWidth - (Math.abs(columnMin) / totalValueRange) * maxWidth
) - 1;
gradientX = Math.round(zeroPosition);
context.translate(gradientX, 0);
} else if (direction === 'RTL') {
// Value is greater than or equal to 0
gradientWidth = Math.round(
(Math.abs(columnMax) / totalValueRange) * maxWidth
);
gradientX = Math.round(leftmostPosition);
context.translate(gradientX + gradientWidth, 0);
context.scale(-1, 1);
}
const gradient = DataBarCellRenderer.getGradient(
gradientWidth,
dataBarColor
);
context.fillStyle = gradient;
context.fillRect(0, dataBarY, gradientWidth, rowHeight);
context.restore(); // Restore gradient translate/scale
} else {
// Draw normal bar
const barColor = Array.isArray(dataBarColor)
? dataBarColor[0]
: dataBarColor;
context.fillStyle = barColor;
context.beginPath();
context.roundRect(dataBarX, dataBarY, dataBarWidth, rowHeight, 1);
context.fill();
}
// Draw markers
if (maxWidth > 0) {
markerXs.forEach((markerX, index) => {
context.fillStyle = markers[index].color;
context.fillRect(markerX, dataBarY, 1, rowHeight);
});
}
// restore clip
context.restore();
const shouldRenderDashedLine = !(
axis === 'directional' &&
((valuePlacement === 'beside' &&
textAlign === 'right' &&
direction === 'LTR') ||
(valuePlacement === 'beside' &&
textAlign === 'left' &&
direction === 'RTL') ||
valuePlacement !== 'beside')
);
// Draw dashed line
if (shouldRenderDashedLine) {
context.strokeStyle = theme.zeroLineColor;
context.beginPath();
context.setLineDash([2, 1]);
context.moveTo(zeroPosition, rowY);
context.lineTo(zeroPosition, rowY + rowHeight);
context.stroke();
}
context.restore();
// Draw tree marker
if (
isFirstColumn &&
isExpandableGridModel(model) &&
model.hasExpandableRows
) {
this.drawCellRowTreeMarker(context, state, row);
}
}
getDataBarRenderMetrics(
context: CanvasRenderingContext2D,
state: GridRenderState,
column: VisibleIndex,
row: VisibleIndex
): DataBarRenderMetrics {
const { metrics, model, theme } = state;
if (!isDataBarGridModel(model)) {
throw new Error('Grid model is not a data bar grid model');
}
const {
firstColumn,
allColumnXs,
allColumnWidths,
allRowYs,
modelColumns,
modelRows,
visibleRows,
} = metrics;
const { cellHorizontalPadding, treeDepthIndent, treeHorizontalPadding } =
theme;
const modelColumn = getOrThrow(modelColumns, column);
const modelRow = getOrThrow(modelRows, row);
const x = getOrThrow(allColumnXs, column);
const y = getOrThrow(allRowYs, row);
const columnWidth = getOrThrow(allColumnWidths, column);
const isFirstColumn = column === firstColumn;
let treeIndent = 0;
if (
isExpandableGridModel(model) &&
model.hasExpandableRows &&
isFirstColumn
) {
treeIndent =
treeDepthIndent * (model.depthForRow(row) + 1) + treeHorizontalPadding;
}
const textAlign = model.textAlignForCell(modelColumn, modelRow);
const {
columnMin,
columnMax,
axis,
valuePlacement,
markers,
direction,
value,
} = model.dataBarOptionsForCell(modelColumn, modelRow, theme);
const longestValueWidth = this.getCachedWidestValueForColumn(
context,
visibleRows,
modelRows,
model,
modelColumn
);
const leftPadding = 2;
const rightPadding =
valuePlacement === 'beside' && textAlign === 'right' ? 2 : 1;
// The value of the total range (e.g. max - column)
let totalValueRange = columnMax - columnMin;
// If min and max are both positive or min and max are equal, the max length is columnMax
if ((columnMax >= 0 && columnMin >= 0) || columnMin === columnMax) {
totalValueRange = columnMax;
} else if (columnMax <= 0 && columnMin <= 0) {
// If min and max are both negative, the max length is the absolute value of columnMin
totalValueRange = Math.abs(columnMin);
}
let maxWidth = columnWidth - treeIndent - rightPadding - leftPadding;
if (valuePlacement === 'beside') {
maxWidth = maxWidth - cellHorizontalPadding - longestValueWidth;
}
if (maxWidth < 0) {
maxWidth = 0;
}
const columnLongest = Math.max(Math.abs(columnMin), Math.abs(columnMax));
// If axis is proportional, totalValueRange is proportional to maxWidth
let dataBarWidth = (Math.abs(value) / totalValueRange) * maxWidth;
if (maxWidth === 0) {
dataBarWidth = 0;
} else if (axis === 'middle') {
// The longest bar is proportional to half of the maxWidth
dataBarWidth = (Math.abs(value) / columnLongest) * (maxWidth / 2);
} else if (axis === 'directional') {
// The longest bar is proportional to the maxWidth
dataBarWidth = (Math.abs(value) / columnLongest) * maxWidth;
}
// Default: proportional, beside, LTR, right text align
// All positions are assuming the left side is 0 and the right side is maxWidth
let zeroPosition =
columnMin >= 0 ? 0 : (Math.abs(columnMin) / totalValueRange) * maxWidth;
let dataBarX =
value >= 0
? zeroPosition
: zeroPosition - (Math.abs(value) / totalValueRange) * maxWidth;
let markerXs = markers.map(marker => {
const { value: markerValue } = marker;
const offset = (Math.abs(markerValue) / totalValueRange) * maxWidth;
return markerValue >= 0 ? zeroPosition + offset : zeroPosition - offset;
});
let leftmostPosition =
valuePlacement === 'beside' && textAlign === 'left'
? cellHorizontalPadding + longestValueWidth + leftPadding
: leftPadding;
let rightmostPosition =
valuePlacement === 'beside' && textAlign === 'right'
? columnWidth - cellHorizontalPadding - longestValueWidth - rightPadding
: rightPadding;
// Proportional, RTL
if (direction === 'RTL') {
zeroPosition =
columnMin >= 0
? columnWidth
: columnWidth - (Math.abs(columnMin) / totalValueRange) * maxWidth;
dataBarX =
value >= 0
? zeroPosition - (value / totalValueRange) * maxWidth
: zeroPosition;
markerXs = markers.map(marker => {
const { value: markerValue } = marker;
return markerValue >= 0
? zeroPosition - (Math.abs(markerValue) / totalValueRange) * maxWidth
: zeroPosition + (Math.abs(markerValue) / totalValueRange) * maxWidth;
});
}
if (axis === 'middle') {
zeroPosition = maxWidth / 2;
if (direction === 'LTR') {
// Middle, LTR
dataBarX =
value >= 0
? zeroPosition
: zeroPosition - (Math.abs(value) / columnLongest) * (maxWidth / 2);
markerXs = markers.map(marker => {
const { value: markerValue } = marker;
return markerValue >= 0
? zeroPosition +
(Math.abs(markerValue) / columnLongest) * (maxWidth / 2)
: zeroPosition -
(Math.abs(markerValue) / columnLongest) * (maxWidth / 2);
});
} else if (direction === 'RTL') {
// Middle, RTL
dataBarX =
value <= 0
? zeroPosition
: zeroPosition - (Math.abs(value) / columnLongest) * (maxWidth / 2);
markerXs = markers.map(marker => {
const { value: markerValue } = marker;
return markerValue <= 0
? zeroPosition +
(Math.abs(markerValue) / columnLongest) * (maxWidth / 2)
: zeroPosition -
(Math.abs(markerValue) / columnLongest) * (maxWidth / 2);
});
}
} else if (axis === 'directional') {
if (direction === 'LTR') {
// Directional, LTR
zeroPosition = 0;
dataBarX = zeroPosition;
markerXs = markers.map(marker => {
const { value: markerValue } = marker;
return (
zeroPosition + (Math.abs(markerValue) / columnLongest) * maxWidth
);
});
} else if (direction === 'RTL') {
// Directional, RTL
zeroPosition = columnWidth;
dataBarX = zeroPosition - (Math.abs(value) / columnLongest) * maxWidth;
markerXs = markers.map(marker => {
const { value: markerValue } = marker;
return (
zeroPosition - (Math.abs(markerValue) / columnLongest) * maxWidth
);
});
}
}
// Offset all values by the actual x value and padding
if (direction === 'LTR') {
zeroPosition += x + leftPadding + treeIndent;
dataBarX += x + leftPadding + treeIndent;
markerXs = markerXs.map(
markerX => markerX + x + leftPadding + treeIndent
);
if (valuePlacement === 'beside' && textAlign === 'left') {
zeroPosition += longestValueWidth + cellHorizontalPadding;
dataBarX += longestValueWidth + cellHorizontalPadding;
markerXs = markerXs.map(
markerX => markerX + longestValueWidth + cellHorizontalPadding
);
}
} else if (direction === 'RTL') {
zeroPosition = zeroPosition + x - rightPadding;
dataBarX = dataBarX + x - rightPadding;
markerXs = markerXs.map(markerX => markerX + x - rightPadding);
if (valuePlacement === 'beside' && textAlign === 'right') {
zeroPosition = zeroPosition - cellHorizontalPadding - longestValueWidth;
dataBarX = dataBarX - cellHorizontalPadding - longestValueWidth;
markerXs = markerXs.map(
markerX => markerX - cellHorizontalPadding - longestValueWidth
);
}
}
leftmostPosition += x + treeIndent;
rightmostPosition += x;
return {
maxWidth,
x: dataBarX,
y,
zeroPosition,
leftmostPosition,
rightmostPosition,
totalValueRange,
dataBarWidth,
markerXs,
};
}
getCachedWidth = memoizeClear(
(context: CanvasRenderingContext2D, text: string): number =>
context.measureText(text).width,
{ max: 10000 }
);
/**
* Returns the width of the widest value in pixels
*/
getCachedWidestValueForColumn = memoizeClear(
(
context: CanvasRenderingContext2D,
visibleRows: readonly VisibleIndex[],
modelRows: VisibleToModelMap,
model: GridModel,
column: ModelIndex
): number => {
let widestValue = 0;
for (let i = 0; i < visibleRows.length; i += 1) {
const row = visibleRows[i];
const modelRow = getOrThrow(modelRows, row);
const text = model.textForCell(column, modelRow);
widestValue = Math.max(widestValue, this.getCachedWidth(context, text));
}
return widestValue;
},
{ max: 1000 }
);
}
export default DataBarCellRenderer;