-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.ts
1311 lines (1118 loc) · 35.9 KB
/
index.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
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
ResponsiveElement,
html,
css,
TemplateResult,
CSSResultGroup,
PropertyValues
} from '@refinitiv-ui/core';
import { customElement } from '@refinitiv-ui/core/decorators/custom-element.js';
import { property } from '@refinitiv-ui/core/decorators/property.js';
import { query } from '@refinitiv-ui/core/decorators/query.js';
import { VERSION } from '../version.js';
import { MicroTaskRunner } from '@refinitiv-ui/utils/async.js';
import { color, ColorCommonInstance } from '@refinitiv-ui/utils/color.js';
import '../canvas/index.js';
import type { Canvas } from '../canvas';
import '../tooltip/index.js';
import { Track } from './helpers/track.js';
import { blend, brighten, darken, isLight, interpolate } from './helpers/color.js';
import type { HeatmapCell, HeatmapConfig, HeatmapTooltipCallback, HeatmapRenderCallback } from './helpers/types';
import { getResponsiveFontSize, getMaximumTextWidth, MIN_FONT_SIZE } from './helpers/text.js';
const MAX_CELL_WIDTH_RATIO = 0.85;
const DEFAULT_CANVAS_RATIO = 0.75; // ratio — 4:3
export type { HeatmapCell, HeatmapXAxis, HeatmapYAxis, HeatmapConfig, HeatmapTooltipCallback, HeatmapRenderCallback, HeatmapCustomisableProperties } from './helpers/types.js';
/**
* A graphical representation of data where the individual
* values contained in a matrix are represented as colors
*/
@customElement('ef-heatmap', {
alias: 'sapphire-heatmap'
})
export class Heatmap extends ResponsiveElement {
/**
* Element version number
* @returns version number
*/
static get version (): string {
return VERSION;
}
/**
* A `CSSResultGroup` that will be used
* to style the host, slotted children
* and the internal template of the element.
* @returns CSS template
*/
static get styles (): CSSResultGroup {
return css`
:host {
display: block;
}
#container{
width: 100%;
height: 100%;
display: flex;
}
#canvas-container {
min-width:0;
display: flex;
width: 100%;
flex-direction: column;
position: relative;
}
#tooltip-overlay {
position: absolute;
}
[part=canvas] {
flex-grow: 1;
}
[part=x-axis] {
display: flex;
align-items: center;
}
[part=y-axis]{
display: flex;
flex-direction: column;
}
.x-axis-item {
text-align: center;
overflow: hidden;
}
.y-axis-item {
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
`;
}
/**
* Heatmap configuration options.
* @type {HeatmapConfig}
*/
@property({ type: Object })
public config: HeatmapConfig | null = null;
/**
* Number of maximum label width that cell can paint in pixel.
* e.g. label-width: 30px; cell label hides when text length reaches 30px.
*/
@property({ type: Number, attribute: 'label-width' })
public labelWidth = 0;
/**
* Hide all labels in the cells
*/
@property({ type: Boolean, attribute: 'label-hidden' })
public labelHidden = false;
/**
* Hide all axes
*/
@property({ type: Boolean, attribute: 'axis-hidden' })
public axisHidden = false;
/**
* Current active cell for internal use
* @private
*/
@property({ type: Object, attribute: false })
/* istanbul ignore next */
public get hoverCell (): HeatmapCell | null {
return this._hoverCell;
}
/* istanbul ignore next */
public set hoverCell (hoverCell: HeatmapCell | null) {
const previousHoverCell = this._hoverCell;
this._hoverCell = hoverCell;
if (this._hoverCell !== previousHoverCell) {
this.requestUpdate('hoverCell', previousHoverCell);
this.hoverCellChanged(this._hoverCell, previousHoverCell);
}
}
/**
* Minimum point of the cell coloring
*/
@property({ type: Number, attribute: 'min-point' })
public minPoint = -1;
/**
* Middle point of the cell coloring
*/
@property({ type: Number, attribute: 'mid-point' })
public midPoint = 0;
/**
* Maximum point of the cell coloring
*/
@property({ type: Number, attribute: 'max-point' })
public maxPoint = 1;
/**
* Enable cell color blending
*/
@property({ type: Boolean })
public blend = false;
/**
* Cell minimum color saturation, value can be from 0 - 1
*/
@property({ type: Number })
public saturation = 0.4;
/**
* Returns data of interactive cell
* @param event an event that occur while the user interacting with element
* @returns data of cell
*/
/* istanbul ignore next */
public getCellDataAtEvent (event: MouseEvent): HeatmapCell | null {
return this.hitTest(event);
}
/**
* A callback function that allows tooltip rendering on cell hover
* @type {HeatmapTooltipCallback}
*/
@property({ type: Function, attribute: false })
public tooltipCallback: HeatmapTooltipCallback | undefined;
/**
* Render callback function use for custom cell properties.
* Accepts custom label, foreground and background color
* @type {HeatmapRenderCallback}
*/
@property({ type: Function, attribute: false })
public renderCallback: HeatmapRenderCallback | undefined;
/**
* HTML canvas DOM used to render heatmap
*/
@query('[part=canvas]', true)
private canvas!: HTMLCanvasElement & Canvas;
/**
* Main component's container DOM
*/
@query('#container', true)
private container!: HTMLElement;
/**
* Cross-box DOM
*/
@query('[part=cross-box]', true)
private crossBox!: HTMLElement;
/**
* Y-axis DOM
*/
@query('[part=y-axis]', true)
private yAxis?: HTMLElement;
/**
* X-axis DOM
*/
@query('[part=x-axis]', true)
private xAxis?: HTMLElement;
/**
* Box containing canvas and x-axis DOM
*/
@query('#canvas-container', true)
private canvasContainer!: HTMLElement;
/**
* Contains a y-axis and a cross box DOM
*/
@query('#y-axis-container', true)
private yAxisBox?: HTMLElement;
/**
* Overlay used for moving target around for rendering tooltip when a cell is hit.
* Canvas alone cannot do this. It is one whole element.
*/
@query('#tooltip-overlay')
private tooltipOverlay!: HTMLElement;
/**
* Current active cell
*/
private _hoverCell: HeatmapCell | null = null;
/**
* Internal cells data storage
*/
private cells: HeatmapCell[] = [];
/**
* Canvas's font color according to theme
*/
private foregroundColor = '';
/**
* Canvas's background color according to theme
*/
private backgroundColor = '';
/**
* Row cells track for easier calculations
*/
private rowTrack = new Track();
/**
* Column cells track for easier calculations
*/
private colTrack = new Track();
/**
* A flag to check if calculated responsive height it been set.
*/
private responsiveHeight = false;
/**
* A flag to check if the component has a size.
*/
private isSizeCalculated = false;
/**
* Use to prevent resizes observer in certain use cases
*/
private updateTimer = 0;
/**
* Use to throttle heatmap painting
*/
private renderTask = new MicroTaskRunner();
/**
* A flag to check if the cell has header enable.
*/
private hasCellHeader = false;
/**
* A flag to check if cell's content is within its boundary
*/
private contentWithinCellBoundary = true;
/**
* Margin around each cell
*/
private cellMargin = 1;
/**
* Above point color that is customisable using CSS variable
*/
private abovePointColor = '';
/**
* Middle point color that is customisable using CSS variable
*/
private midPointColor = '';
/**
* Below point color that is customisable using CSS variable
*/
private belowPointColor = '';
/**
* Gets the computed style of the canvas element
* @returns computed canvas style
*/
private get canvasStyle (): CSSStyleDeclaration {
return getComputedStyle(this.canvas);
}
/**
* Gets the 2D context of the canvas element
* @returns 2D canvas context
*/
private get canvasContext (): CanvasRenderingContext2D | null {
return this.canvas.context;
}
/**
* Safely gets the row data
* @returns array of row data
*/
private get rows (): HeatmapCell[][] {
return this.config && Array.isArray(this.config?.data) ? this.config.data : [];
}
/**
* Get row count
* @returns count of rows
*/
private get rowCount (): number {
return this.rows ? this.rows.length : 0;
}
/**
* Get column count
* @returns count of columns
*/
private get columnCount (): number {
let result = 0;
this.rows?.forEach(columns => {
if (columns.length > result) {
result = columns.length;
}
});
return result;
}
constructor () {
super();
/** @ignore */
this.onResize = this.onResize.bind(this);
/** @ignore */
this.onMouseMove = this.onMouseMove.bind(this);
/** @ignore */
this.stopAnimation = this.stopAnimation.bind(this);
/** @ignore */
this.tooltipRenderer = this.tooltipRenderer.bind(this);
/** @ignore */
this.tooltipCondition = this.tooltipCondition.bind(this);
/** @ignore */
this.onMouseLeave = this.onMouseLeave.bind(this);
}
/**
* Called when the element’s DOM has been updated and rendered
* @param changedProperties changed properties
* @returns {void}
*/
protected updated (changedProperties: PropertyValues): void {
if (changedProperties.has('labelHidden')) {
this.labelHiddenChanged();
}
// Re-paints whole canvas when at least one of the following properties changes
if (
changedProperties.has('config')
|| changedProperties.has('blend')
|| changedProperties.has('minPoint')
|| changedProperties.has('midPoint')
|| changedProperties.has('maxPoint')
|| changedProperties.has('saturation')
|| changedProperties.has('axisHidden')
|| changedProperties.has('labelWidth')
) {
this.prepareAndPaint();
}
}
/**
* Handles resize events
* @returns {void}
*/
private onCanvasResize (): void {
this.prepareAndPaint();
}
/**
* Handles mouse moving on heatmap canvas
* @param event mousemove event
* @returns {void}
*/
/* istanbul ignore next */
private onMouseMove (event: MouseEvent): void {
if (event.composedPath().includes(this.canvas) || this.tooltipCallback && this.tooltipOverlay === event.target) {
this.hoverCell = this.hitTest(event);
}
else {
this.hoverCell = null;
}
}
/**
* Handles when mouse moving outside element
* @param event mouseleave event
* @returns {void}
*/
/* istanbul ignore next */
private onMouseLeave (): void {
this.hoverCell = null;
}
/**
* Handles heatmap resizes
* @returns {void}
*/
private onResize (): void {
this.updateTimer = 0;
if (!this.isSizeCalculated) {
if (this.offsetWidth || this.offsetHeight) {
this.isSizeCalculated = true;
}
}
if (this.isSizeCalculated) {
const spacing = parseFloat(this.getComputedVariable('--spacing', '0'));
this.cellMargin = spacing / 2;
}
// calculate responsive height
if (this.responsiveHeight || !this.offsetHeight) {
const width = this.offsetWidth;
if (width) {
const newHeight = `${Math.floor(DEFAULT_CANVAS_RATIO * width)}px`;
if (this.style.height !== newHeight) {
// set height to outermost container, so that heatmap's height can be override
this.container.style.height = newHeight;
this.responsiveHeight = true;
this.updateTimer = -1; // Prevent resizeObserver from executing this method in the next call
}
}
}
this.prepareAndPaint();
}
/**
* Initialize row track
* @returns {void}
*/
private initialiseRowTrack (): void {
this.rowTrack.init(this.offsetHeight, this.rowCount);
this.rowTrack.margin = this.cellMargin;
}
/**
* Initialize column track
* @returns {void}
*/
private initialiseColumnTrack (): void {
this.colTrack.init(this.offsetWidth, this.columnCount);
this.colTrack.margin = this.cellMargin;
}
/**
* Hit testing on heatmap
* @param event mouse event
* @returns cell
*/
/* istanbul ignore next */
private hitTest (event: MouseEvent): HeatmapCell | null {
const box = this.canvas.getBoundingClientRect();
const x = event.clientX - box.left;
const y = event.clientY - box.top;
const row = this.rowTrack.hitTest(y);
const column = this.colTrack.hitTest(x);
return this.getCellByLocation(row, column);
}
/**
* Get a cell, using row and column coordinates
* @param row row index
* @param column column index
* @returns cell
*/
/* istanbul ignore next */
private getCellByLocation (row: number, column: number): HeatmapCell | null {
if (row < 0 || row >= this.rowCount) {
return null;
}
if (column < 0 || column >= this.columnCount) {
return null;
}
return this.cells[row * this.columnCount + column] || null;
}
/**
* Update overlay position
* @param cell cell information for correct overlay
* @returns {void}
*/
/* istanbul ignore next */
private updateTooltipOverlayPosition (cell: HeatmapCell): void {
// Compensate x-axis height for overlay when x-axis is at top position
let marginOverlayTop = 0;
if (this.config?.xAxis && this.xAxis?.offsetHeight) {
marginOverlayTop = this.config.xAxis.position === 'bottom' ? 0 : this.xAxis?.offsetHeight;
}
// Update overlay position
this.tooltipOverlay.style.left = `${cell.x}px`;
this.tooltipOverlay.style.top = `${cell.y + marginOverlayTop}px`;
this.tooltipOverlay.style.width = `${cell.width}px`;
this.tooltipOverlay.style.height = `${cell.height}px`;
}
/**
* Called upon active cell changes i.e cell hovering
* @param cell current active cell
* @param previousCell previous active cell
* @returns {void}
*/
/* istanbul ignore next */
private hoverCellChanged (cell: HeatmapCell | null, previousCell: HeatmapCell | null): void {
if (cell && cell.value !== null) {
if (this.tooltipCallback) {
this.updateTooltipOverlayPosition(cell);
}
// faded color depending on cell font color, light font darkens the cell background and vice versa
const fontColor = color(getComputedStyle(this.canvas).color) as ColorCommonInstance;
const fadedColor = isLight(fontColor) ? darken(cell.backgroundColor) : brighten(cell.backgroundColor);
this.fade(cell, cell.backgroundColor, fadedColor, 100);
}
// returns color of previous cell to default cell color
if (previousCell && previousCell.value !== null) {
previousCell.foregroundColor = this.foregroundColor;
this.fade(previousCell, previousCell.backgroundColor, this.getBackgroundColor(previousCell.value), 300);
}
}
/**
* Called upon label-hidden attribute changes
* @returns {void}
*/
private labelHiddenChanged (): void {
this.paintAllCellBackground();
if (this.hasCellHeader) {
this.paintAllHeader();
}
if (!this.labelHidden) {
this.paintAllLabel();
}
}
/**
* Handles heatmap resizes
* @ignore
* @returns {void}
*/
public resizedCallback (): void {
if (this.updateTimer) {
this.updateTimer = 0;
}
else {
// split layout updating to another execution-loop
// to prevents resizeObserver triggers resize-loop-error
this.updateTimer = window.setTimeout(this.onResize);
}
}
/**
* Stop any current animations on a cell.
* @param {HeatmapCell} cell cell to stop the animation on
* @returns {void}
*/
/* istanbul ignore next */
private stopAnimation (cell: HeatmapCell): void {
if (cell.animationFrame) {
cancelAnimationFrame(cell.animationFrame);
}
}
/**
* Stops all animations on a cell
* @returns {void}
*/
private stopAllAnimations (): void {
this.cells.forEach(this.stopAnimation);
}
/**
* Clear a cell on canvas
* @param cell cell object
* @returns {void}
*/
/* istanbul ignore next */
private resetCell (cell: HeatmapCell): void {
this.canvasContext?.clearRect(
cell.x,
cell.y,
cell.width,
cell.height
);
}
/**
* Fades a cell's background from one color to another
* @param cell to fade
* @param from initial cell color
* @param to color after faded
* @param duration fading animation duration
* @param delay fading animation delay
* @returns {void}
*/
/* istanbul ignore next */
private fade (cell: HeatmapCell, from: string, to: string, duration: number): void {
const start = performance.now();
const end = start + duration;
const fadingAnimation: FrameRequestCallback = (time: number): void => {
cell.x = this.colTrack.getContentStart(cell.colIndex);
cell.y = this.rowTrack.getContentStart(cell.rowIndex);
cell.width = this.colTrack.getContentSize(cell.colIndex);
cell.height = this.rowTrack.getContentSize(cell.rowIndex);
if (cell.animationFrame) {
cancelAnimationFrame(cell.animationFrame);
}
const colorFadingFactor = Math.max(Math.min((time - start) / (end - start), 1), 0);
// Reset cell and prepare for re-paint
this.resetCell(cell);
// Assign new cell background color after fading
cell.backgroundColor = interpolate(from, to)(colorFadingFactor);
this.paintCell(cell);
if (colorFadingFactor < 1) {
cell.animationFrame = requestAnimationFrame(fadingAnimation);
}
};
if (cell.animationFrame) {
cancelAnimationFrame(cell.animationFrame);
}
cell.animationFrame = requestAnimationFrame(fadingAnimation);
}
/**
* Converts the input data into usable cell data
* @returns {void}
*/
private calculateCellData (): void {
// Reset cell
this.cells = [];
if (!this.axisHidden) {
if (this.yAxis && this.config?.yAxis) {
this.rowTrack.init(this.yAxis.offsetHeight, this.rowCount);
}
if (this.xAxis && this.config?.xAxis) {
this.colTrack.init(this.xAxis.offsetWidth, this.columnCount);
}
}
// TODO: ensure that cell size must always be larger than cell margin
for (let rowIndex = 0; rowIndex < this.rowTrack.laneCount; rowIndex++) {
for (let columnIndex = 0; columnIndex < this.colTrack.laneCount; columnIndex++) {
const cell: HeatmapCell = this.rows[rowIndex][columnIndex];
const cellValue = cell ? cell.value : null;
const cellLabel = cellValue !== null && typeof cellValue === 'number' ? cellValue.toFixed(2) : '';
const cellHeader = cell && cell.header ? cell.header : '';
const cellIndex = rowIndex * this.colTrack.laneCount + columnIndex;
const foregroundColor = this.foregroundColor;
const backgroundColor = this.getBackgroundColor(cellValue)?.toString() || '';
if (cellHeader) {
this.hasCellHeader = true;
}
this.cells[cellIndex] = {
rowIndex: rowIndex,
colIndex: columnIndex,
x: this.colTrack.getContentStart(columnIndex),
y: this.rowTrack.getContentStart(rowIndex),
width: this.colTrack.getContentSize(columnIndex),
height: this.rowTrack.getContentSize(rowIndex),
value: cellValue,
header: cellHeader,
label: cellLabel,
foregroundColor: foregroundColor,
defaultBackground: backgroundColor,
backgroundColor: backgroundColor
};
}
}
}
/**
* Performs check to see if everything is ready,
* converts data into usable cells and then
* paints to the canvas.
* @returns {void}
*/
private prepareAndPaint (): void {
if (!!this.canvas && this.config) {
this.renderTask.schedule(() => {
this.stopAllAnimations();
this.initialiseColumnTrack();
this.initialiseRowTrack();
if (!this.axisHidden) {
this.renderAxisX();
this.renderAxisY();
}
this.getCellBaseColors();
this.getCanvasColors();
this.calculateCellData();
this.paint();
});
}
}
/**
* Paints all cells to the canvas
* @returns {void}
*/
private paint (): void {
if (!this.isSizeCalculated) {
return;
}
if (this.renderCallback) {
this.retrieveAllCustomCellProperties();
}
this.paintAllCellBackground();
if (this.canPaintText()) {
if (!this.labelHidden) {
this.paintAllLabel();
}
if (this.hasCellHeader) {
this.paintAllHeader();
}
}
}
/**
* Paints label to all cells
* @returns {void}
*/
private paintAllLabel (): void {
for (let index = 0; index < this.cells.length; index++) {
this.paintLabel(this.cells[index]);
}
}
/**
* Calculates space between header and label using cell's height
* Maximum 10 pixels
* @param cellHeight in pixels
* @returns in pixels
*/
private calculateHeaderMargin (cellHeight: number): number {
const margin = (cellHeight / 10) * 2;
return margin > 10 ? 10 : margin;
}
/**
* Paints label to a single cell
* @param cell cell to paint
* @returns {void}
*/
private paintLabel (cell: HeatmapCell): void {
const margin = cell.header ? this.calculateHeaderMargin(cell.height) : 0;
const label = typeof cell.customLabel === 'string' ? cell.customLabel : cell.label;
if (this.canvasContext) {
this.canvasContext.fillStyle = cell.customForegroundColor || cell.foregroundColor;
this.canvasContext.fillText(label || '', cell.x + cell.width / 2, (cell.y + 1 + cell.height / 2) + margin);
}
}
/**
* Check if the text (label / header and label) can be paint on the cell
* @returns true if text is within cell's boundary
*/
/* istanbul ignore next */
private canPaintText (): boolean {
const canvas = this.canvasContext;
if (!canvas) {
return false;
}
const fontRatio = this.responsiveHeight ? 0.3 : 0.4;
const fontFamily = getComputedStyle(this).fontFamily;
const contentWidth = this.colTrack.getContentSize(0);
const contentHeight = this.rowTrack.getContentSize(0);
if (contentWidth <= 0 || contentHeight <= 0) {
this.contentWithinCellBoundary = false;
return this.contentWithinCellBoundary;
}
let fontSize = getResponsiveFontSize(fontRatio, contentHeight, contentWidth);
canvas.textAlign = 'center';
canvas.textBaseline = 'middle';
canvas.font = `${fontSize}px ${fontFamily}`;
let isWithinMinCellWidth = ((this.labelWidth || getMaximumTextWidth(canvas, this.cells, this.hasCellHeader)) / contentWidth) < MAX_CELL_WIDTH_RATIO;
// If label width is still more than 85% of the cell width, try to reduce to smallest possible font-size to display label.
if (!isWithinMinCellWidth && fontSize !== MIN_FONT_SIZE) {
while (!isWithinMinCellWidth) {
canvas.font = `${fontSize}px ${fontFamily}`; // Should assigned new font size to canvas before calculated again.
isWithinMinCellWidth = ((this.labelWidth || getMaximumTextWidth(canvas, this.cells, this.hasCellHeader)) / contentWidth) < MAX_CELL_WIDTH_RATIO;
// Stops when reaches minimum font-size
if (fontSize === MIN_FONT_SIZE) {
break;
}
if (!isWithinMinCellWidth && fontSize > MIN_FONT_SIZE) {
fontSize -= 1;
}
}
}
const isWithinMinCellHeight = this.hasCellHeader ? (fontSize * 2) < contentHeight : fontSize < contentHeight;
this.contentWithinCellBoundary = isWithinMinCellWidth && isWithinMinCellHeight;
return this.contentWithinCellBoundary;
}
/**
* Calculate cell background color based on the current cell data value
* @param value cell value
* @returns calculated color
*/
/* istanbul ignore next */
private getBackgroundColor (value: number | null): string {
if (value === null) {
return this.backgroundColor;
}
let saturation = this.blend ? 0 : this.saturation;
// Can only have value from 0 to 1
if (saturation > 1) {
saturation = 1;
}
else if (saturation < 0) {
saturation = 0;
}
const factor = this.calculateColorFactor(value, saturation);
if (this.blend) {
return blend(this.belowPointColor, this.abovePointColor, this.backgroundColor, factor);
}
else if (factor >= 0) {
return interpolate(this.midPointColor, this.abovePointColor)(factor);
}
else {
return interpolate(this.midPointColor, this.belowPointColor)(-factor);
}
}
/**
* Calculate the color mixing factor from 0 - 1
* @param value cell value
* @param saturation color saturation level
* @returns factor
*/
/* istanbul ignore next */
private calculateColorFactor (value: number, saturation: number): number {
if (value >= this.maxPoint) {
return 1;
}
if (value <= this.minPoint) {
return -1;
}
if (value === this.midPoint) {
return saturation;
}
const saturateRatio = 1 - saturation;
if (value > this.midPoint) {
return ((value - this.midPoint) / (this.maxPoint - this.midPoint) * saturateRatio) + saturation;
}
else {
return ((value - this.midPoint) / (this.midPoint - this.minPoint) * saturateRatio) - saturation;
}
}
/**
* Get and stores canvas color from computed canvas style
* @returns {void}
*/
private getCanvasColors (): void {
this.foregroundColor = this.canvasStyle.color;
this.backgroundColor = this.canvasStyle.backgroundColor;
}
/**
* Get and stores cell colors based on theme or custom css variables
* @returns {void}
*/
private getCellBaseColors (): void {
this.abovePointColor = this.getComputedVariable('--above-point-color');
this.midPointColor = this.getComputedVariable('--mid-point-color');
this.belowPointColor = this.getComputedVariable('--below-point-color');
}
/**
* Retrieve custom cell properties for a single cell
* @param {HeatmapCell} cell cell to assign colours
* @returns {void}
*/
private retrieveCustomCellProperties (cell: HeatmapCell): void {
const customCellProperties = this.renderCallback ? this.renderCallback(Object.assign({}, cell)) : null;
if (customCellProperties) {
cell.customLabel = customCellProperties.label;
cell.customBackgroundColor = customCellProperties.backgroundColor;
cell.customForegroundColor = customCellProperties.foregroundColor;
}
}
/**
* Retrieves all custom call properties
* @returns {void}
*/
private retrieveAllCustomCellProperties (): void {
for (let index = 0; index < this.cells.length; index++) {
this.retrieveCustomCellProperties(this.cells[index]);
}
}