-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathCdcChartComponent.tsx
More file actions
1518 lines (1361 loc) · 57.9 KB
/
CdcChartComponent.tsx
File metadata and controls
1518 lines (1361 loc) · 57.9 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
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 React, { useState, useEffect, useCallback, useRef, useId, useContext, useReducer, useMemo } from 'react'
// IE11
import ResizeObserver from 'resize-observer-polyfill'
import 'whatwg-fetch'
// Core components
import fetchRemoteData from '@cdc/core/helpers/fetchRemoteData'
import Layout from '@cdc/core/components/Layout'
import Confirm from '@cdc/core/components/elements/Confirm'
import Error from '@cdc/core/components/elements/Error'
import SkipTo from '@cdc/core/components/elements/SkipTo'
import Title from '@cdc/core/components/ui/Title'
import DataTable from '@cdc/core/components/DataTable'
// Local Components
import LegendWrapper from './components/LegendWrapper'
//types
import { type DashboardConfig } from '@cdc/dashboard/src/types/DashboardConfig'
import type { TableConfig } from '@cdc/core/components/DataTable/types/TableConfig'
import { AllChartsConfig, ChartConfig } from './types/ChartConfig'
import { Pivot } from '@cdc/core/types/Table'
import { Runtime } from '@cdc/core/types/Runtime'
import { Label } from './types/Label'
// External Libraries
import ParentSize from '@visx/responsive/lib/components/ParentSize'
import { timeParse, timeFormat } from 'd3-time-format'
import parse from 'html-react-parser'
import _ from 'lodash'
// Primary Components
import ConfigContext, { ChartDispatchContext } from './ConfigContext'
import PieChart from './components/PieChart'
import SankeyChart from './components/Sankey'
import LinearChart from './components/LinearChart'
import { isDateScale } from '@cdc/core/helpers/cove/date'
import { twoColorPalette } from '@cdc/core/data/colorPalettes'
import { filterChartColorPalettes } from '@cdc/core/helpers/filterColorPalettes'
import SparkLine from './components/Sparkline'
import Legend from './components/Legend'
import WarmingStripesGradientLegend from './components/WarmingStripes/WarmingStripesGradientLegend'
import defaults from './data/initial-state'
import EditorPanel from './components/EditorPanel'
import { abbreviateNumber } from './helpers/abbreviateNumber'
import { handleChartTabbing } from './helpers/handleChartTabbing'
import { handleChartAriaLabels } from './helpers/handleChartAriaLabels'
import { lineOptions } from './helpers/lineOptions'
import { handleLineType } from './helpers/handleLineType'
import { handleRankByValue } from './helpers/handleRankByValue'
import { generateColorsArray } from '@cdc/core/helpers/generateColorsArray'
import { processMarkupVariables } from '@cdc/core/helpers/markupProcessor'
import Loading from '@cdc/core/components/Loading'
import Filters from '@cdc/core/components/Filters'
import MediaControls from '@cdc/core/components/MediaControls'
import Annotation from './components/Annotations'
import { getVisibleAnnotations } from './components/Annotations/helpers/getVisibleAnnotations'
// Core Helpers
import { DataTransform } from '@cdc/core/helpers/DataTransform'
import { isLegendWrapViewport } from '@cdc/core/helpers/viewports'
import { missingRequiredSections } from '@cdc/core/helpers/missingRequiredSections'
import { filterVizData } from '@cdc/core/helpers/filterVizData'
import { addValuesToFilters } from '@cdc/core/helpers/addValuesToFilters'
import { publish, subscribe, unsubscribe } from '@cdc/core/helpers/events'
import useDataVizClasses from '@cdc/core/helpers/useDataVizClasses'
import numberFromString from '@cdc/core/helpers/numberFromString'
import getViewport from '@cdc/core/helpers/getViewport'
import isNumber from '@cdc/core/helpers/isNumber'
import coveUpdateWorker from '@cdc/core/helpers/coveUpdateWorker'
import EditorContext from '@cdc/core/contexts/EditorContext'
import { EDITOR_WIDTH } from '@cdc/core/helpers/constants'
import { extractCoveData, updateVegaData } from '@cdc/core/helpers/vegaConfig'
// Local helpers
import { isConvertLineToBarGraph } from './helpers/isConvertLineToBarGraph'
import { getBoxPlotConfig } from './helpers/getBoxPlotConfig'
import { getComboChartConfig } from './helpers/getComboChartConfig'
import { getExcludedData } from './helpers/getExcludedData'
import { getColorScale } from './helpers/getColorScale'
import { getTransformedData } from './helpers/getTransformedData'
import { getPiePercent } from './helpers/getPiePercent'
import { prepareSmallMultiplesDataTable } from './helpers/smallMultiplesHelpers'
// styles
import './scss/main.scss'
import { getInitialState, reducer } from './store/chart.reducer'
import { VizFilter } from '@cdc/core/types/VizFilter'
import { getNewRuntime } from './helpers/getNewRuntime'
import FootnotesStandAlone from '@cdc/core/components/Footnotes/FootnotesStandAlone'
import { Datasets } from '@cdc/core/types/DataSet'
import { publishAnalyticsEvent } from '@cdc/core/helpers/metrics/helpers'
import cloneConfig from '@cdc/core/helpers/cloneConfig'
import { getVizTitle, getVizSubType } from '@cdc/core/helpers/metrics/utils'
interface CdcChartProps {
config?: ChartConfig
isEditor?: boolean
isDebug?: boolean
isDashboard?: boolean
setConfig?: (config: ChartConfig) => void
setEditing?: (editing: boolean) => void
hostname?: string
link?: string
setSharedFilter?: (filter: any) => void
setSharedFilterValue?: (value: any) => void
dashboardConfig?: DashboardConfig
datasets?: Datasets
interactionLabel: string
}
const CdcChart: React.FC<CdcChartProps> = ({
config: configObj,
isEditor = false,
isDebug = false,
isDashboard = false,
setConfig: setParentConfig,
setEditing,
link,
setSharedFilter,
setSharedFilterValue,
dashboardConfig,
datasets,
interactionLabel
}) => {
const transform = new DataTransform()
const initialState = getInitialState(configObj)
const [state, dispatch] = useReducer(reducer, initialState)
const {
config,
stateData,
excludedData,
filteredData,
currentViewport,
isLoading,
dimensions,
container,
coveLoadedEventRan,
imageId,
seriesHighlight,
colorScale
} = state
const { description, visualizationType } = config
const svgRef = useRef(null)
const editorContext = useContext(EditorContext)
const [externalFilters, setExternalFilters] = useState<any[]>()
const setConfig = (newConfig: ChartConfig): void => {
dispatch({ type: 'SET_CONFIG', payload: newConfig })
if (isEditor && !isDashboard) {
editorContext.setTempConfig(newConfig)
}
}
const legendRef = useRef(null)
const parentRef = useRef(null)
const handleDragStateChange = isDragging => {
dispatch({ type: 'SET_DRAG_ANNOTATIONS', payload: isDragging })
}
// Destructure items from config for more readable JSX
let { legend, title } = config
// Process markup variables for text fields (memoized to prevent re-processing on every render)
// Note: XSS Safety - The processed content is parsed using html-react-parser which sanitizes
// HTML input by default. The markup processor returns plain text with user data substituted.
const processedTextFields = useMemo(() => {
if (!config.enableMarkupVariables || !config.markupVariables?.length) {
return {
title,
superTitle: config.superTitle,
introText: config.introText,
legacyFootnotes: config.legacyFootnotes,
description: config.description
}
}
return {
title: title
? processMarkupVariables(title, config.data || [], config.markupVariables, {
isEditor,
filters: config.filters || []
}).processedContent
: title,
superTitle: config.superTitle
? processMarkupVariables(config.superTitle, config.data || [], config.markupVariables, {
isEditor,
filters: config.filters || []
}).processedContent
: config.superTitle,
introText: config.introText
? processMarkupVariables(config.introText, config.data || [], config.markupVariables, {
isEditor,
filters: config.filters || []
}).processedContent
: config.introText,
legacyFootnotes: config.legacyFootnotes
? processMarkupVariables(config.legacyFootnotes, config.data || [], config.markupVariables, {
isEditor,
filters: config.filters || []
}).processedContent
: config.legacyFootnotes,
description: config.description
? processMarkupVariables(config.description, config.data || [], config.markupVariables, {
isEditor,
filters: config.filters || []
}).processedContent
: config.description
}
}, [
config.enableMarkupVariables,
config.markupVariables,
config.data,
config.filters,
title,
config.superTitle,
config.introText,
config.legacyFootnotes,
config.description,
isEditor
])
// Destructure processed values
title = processedTextFields.title
const processedSuperTitle = processedTextFields.superTitle
const processedIntroText = processedTextFields.introText
const processedLegacyFootnotes = processedTextFields.legacyFootnotes
const processedDescription = processedTextFields.description
// Note: Axis labels are processed within updateConfig to ensure they use the correct data
// set defaults on titles if blank AND only in editor
if (isEditor) {
if (!title || title === '') title = 'Chart Title'
}
if (config.table && (!config.table?.label || config.table?.label === '')) config.table.label = 'Data Table'
const { lineDatapointClass, contentClasses, sparkLineStyles } = useDataVizClasses(config)
const legendId = useId()
const hasDateAxis =
(config.xAxis || config.yAxis) && ['date-time', 'date'].includes((config.xAxis || config.yAxis).type)
const dataTableDefaultSortBy = hasDateAxis && config.xAxis.dataKey
const convertLineToBarGraph = isConvertLineToBarGraph(config, filteredData)
const prepareConfig = (loadedConfig: ChartConfig) => {
// Create defaults without version to avoid overriding legacy configs
const defaultsWithoutPalette = { ...defaults }
// Only remove palette defaults for legacy (v1) configs
// New configs and v2 configs should get the v2 palette defaults
if (loadedConfig?.general?.palette || (!loadedConfig?.general && !loadedConfig?.color)) {
// Keep palette defaults for:
// 1. Configs that already have general.palette (v2 configs)
// 2. New configs (no general section and no legacy color property)
} else {
// Remove palette defaults for legacy configs that have color but no general.palette
delete defaultsWithoutPalette.general?.palette
}
let newConfig = { ...defaultsWithoutPalette, ...loadedConfig }
_.defaultsDeep(newConfig, {
table: { showVertical: false }
})
_.set(newConfig, 'table.show', _.get(newConfig, 'table.show', !isDashboard))
_.forEach(newConfig.series, series => {
_.defaults(series, {
tooltip: true,
axis: 'Left'
})
})
if (newConfig.visualizationType === 'Bump Chart') {
newConfig.xAxis.type === 'date-time'
}
if (!isDashboard) return coveUpdateWorker(newConfig)
return newConfig
}
const getProcessedAxisLabels = useCallback(
(targetConfig: AllChartsConfig, dataSource: any[] = []) => {
let processedXAxis = targetConfig.xAxis?.label
let processedYAxis = targetConfig.yAxis?.label
if (targetConfig.enableMarkupVariables && targetConfig.markupVariables?.length) {
if (targetConfig.xAxis?.label) {
processedXAxis = processMarkupVariables(
targetConfig.xAxis.label,
dataSource || [],
targetConfig.markupVariables,
{
isEditor,
filters: targetConfig.filters || []
}
).processedContent
}
if (targetConfig.yAxis?.label) {
processedYAxis = processMarkupVariables(
targetConfig.yAxis.label,
dataSource || [],
targetConfig.markupVariables,
{
isEditor,
filters: targetConfig.filters || []
}
).processedContent
}
}
const isHorizontalVariant =
((targetConfig.visualizationType === 'Bar' || targetConfig.visualizationType === 'Box Plot') &&
targetConfig.orientation === 'horizontal') ||
['Deviation Bar', 'Paired Bar', 'Forest Plot'].includes(targetConfig.visualizationType)
const runtimeXAxisLabel = isHorizontalVariant
? processedYAxis ?? (targetConfig.yAxis as any)?.yAxis?.label ?? targetConfig.yAxis?.label
: processedXAxis ?? targetConfig.xAxis?.label
const runtimeYAxisLabel = isHorizontalVariant
? processedXAxis ?? (targetConfig.xAxis as any)?.xAxis?.label ?? targetConfig.xAxis?.label
: processedYAxis ?? targetConfig.yAxis?.label
return { processedXAxis, processedYAxis, runtimeXAxisLabel, runtimeYAxisLabel, isHorizontalVariant }
},
[isEditor]
)
const updateConfig = (_config: AllChartsConfig, dataOverride?: any[]) => {
const newConfig = cloneConfig(_config)
let data = dataOverride || stateData
data = handleRankByValue(data, newConfig)
const { processedXAxis, processedYAxis, runtimeXAxisLabel, runtimeYAxisLabel, isHorizontalVariant } =
getProcessedAxisLabels(newConfig, data || [])
// Deeper copy
Object.keys(defaults).forEach(key => {
if (newConfig[key] && 'object' === typeof newConfig[key] && !Array.isArray(newConfig[key])) {
newConfig[key] = { ...defaults[key], ...newConfig[key] }
}
})
const newExcludedData: any[] = getExcludedData(newConfig, dataOverride || stateData)
dispatch({ type: 'SET_EXCLUDED_DATA', payload: newExcludedData })
// After data is grabbed, loop through and generate filter column values if there are any
let currentData: any[] = []
if (newConfig.filters) {
const filtersWithValues = addValuesToFilters(newConfig.filters, newExcludedData)
currentData = filterVizData(filtersWithValues, newExcludedData)
dispatch({ type: 'SET_FILTERED_DATA', payload: currentData })
}
if (newConfig.xAxis.type === 'date-time' && config.orientation === 'horizontal') {
newConfig.xAxis.type = 'date'
}
//Enforce default values that need to be calculated at runtime
// Preserve error messages that were set outside of updateConfig (e.g., from pattern settings)
const existingErrorMessage = _config.runtime?.editorErrorMessage || ''
const isPieChartValidationError =
existingErrorMessage === 'Data column section must be set for pie charts.' ||
existingErrorMessage === 'Segment labels section must be set for pie charts.' ||
existingErrorMessage === 'Data column and Segment labels sections must be set for pie charts.'
const shouldPreserveError = existingErrorMessage && !isPieChartValidationError
newConfig.runtime = {} as Runtime
newConfig.runtime.series = _.cloneDeep(newConfig.series)
newConfig.runtime.seriesLabels = {}
newConfig.runtime.seriesLabelsAll = []
newConfig.runtime.originalXAxis = newConfig.xAxis
if (newConfig.visualizationType === 'Pie') {
// Use the same data that will be passed to PieChart (after exclusions and filters)
const pieData = currentData.length > 0 ? currentData : newExcludedData
newConfig.runtime.seriesKeys = _.uniq(pieData.map(d => d[newConfig.xAxis.dataKey]))
newConfig.runtime.seriesLabelsAll = newConfig.runtime.seriesKeys
} else {
const finalData = dataOverride || newConfig.formattedData || newConfig.data
newConfig.runtime.seriesKeys = (newConfig.runtime.series || []).flatMap(series => {
if (series.dynamicCategory) {
_.remove(newConfig.runtime.seriesLabelsAll, label => label === series.dataKey)
_.remove(newConfig.runtime.series, s => s.dataKey === series.dataKey)
// grab the dynamic series keys from the data
const seriesKeys: string[] = _.uniq(finalData.map(d => d[series.dynamicCategory]))
// for each of those keys perform side effects
seriesKeys.forEach(dataKey => {
newConfig.runtime.seriesLabels[dataKey] = dataKey
newConfig.runtime.seriesLabelsAll.push(dataKey)
newConfig.runtime.series.push({
dataKey,
type: series.type,
lineType: series.lineType,
originalDataKey: series.dataKey,
dynamicCategory: series.dynamicCategory,
tooltip: true
})
})
// return the series keys
return seriesKeys
} else {
newConfig.runtime.seriesLabels[series.dataKey] = series.name || series.label || series.dataKey
newConfig.runtime.seriesLabelsAll.push(series.name || series.dataKey)
// return the series keys
return [series.dataKey]
}
})
}
if (newConfig.visualizationType === 'Box Plot' && newConfig.series) {
const [plots, categories] = getBoxPlotConfig(newConfig, stateData)
newConfig.boxplot['categories'] = categories
newConfig.boxplot.plots = plots
newConfig.yAxis.labelPlacement = 'On Date/Category Axis'
}
if (newConfig.visualizationType === 'Combo' && newConfig.series) {
newConfig.runtime = getComboChartConfig(newConfig)
}
if (newConfig.visualizationType === 'Forecasting' && newConfig.series) {
newConfig.runtime.forecastingSeriesKeys = []
newConfig.series.forEach(series => {
if (series.type === 'Forecasting') {
newConfig.runtime.forecastingSeriesKeys.push(series)
}
})
// Default to date scaling type for Forecasting charts
if (newConfig.xAxis.type === 'categorical') {
newConfig.xAxis.type = 'date'
// Initialize date parsing formats if they don't exist
if (!newConfig.xAxis.dateParseFormat) {
newConfig.xAxis.dateParseFormat = '%Y-%m-%d'
}
if (!newConfig.xAxis.dateDisplayFormat) {
newConfig.xAxis.dateDisplayFormat = '%Y-%m-%d'
}
}
}
if (newConfig.visualizationType === 'Area Chart' && newConfig.series) {
newConfig.runtime.areaSeriesKeys = []
newConfig.series.forEach(series => {
newConfig.runtime.areaSeriesKeys.push({ ...series, type: 'Area Chart' })
})
newConfig.visualizationSubType = 'stacked'
}
if (isHorizontalVariant) {
// For horizontal charts, axes are swapped, so processedYAxis goes to runtime.xAxis and vice versa
const horizontalXAxisSource = _.cloneDeep((newConfig.yAxis as any)?.yAxis || newConfig.yAxis)
const horizontalYAxisSource = _.cloneDeep((newConfig.xAxis as any)?.xAxis || newConfig.xAxis)
newConfig.runtime.xAxis = {
...horizontalXAxisSource,
label: runtimeXAxisLabel ?? horizontalXAxisSource?.label
}
newConfig.runtime.yAxis = {
...horizontalYAxisSource,
label: runtimeYAxisLabel ?? horizontalYAxisSource?.label
}
newConfig.runtime.yAxis.labelOffset *= -1
newConfig.runtime.horizontal = false
newConfig.orientation = 'horizontal'
// remove after COVE supports categorical axis on horizonatal bars
newConfig.yAxis.type = newConfig.yAxis.type === 'categorical' ? 'linear' : newConfig.yAxis.type
} else if (
['Scatter Plot', 'Area Chart', 'Line', 'Forecasting'].includes(newConfig.visualizationType) &&
!convertLineToBarGraph
) {
newConfig.runtime.xAxis = { ...newConfig.xAxis, label: runtimeXAxisLabel ?? newConfig.xAxis.label }
newConfig.runtime.yAxis = { ...newConfig.yAxis, label: runtimeYAxisLabel ?? newConfig.yAxis.label }
newConfig.runtime.horizontal = false
newConfig.orientation = 'vertical'
} else {
newConfig.runtime.xAxis = { ...newConfig.xAxis, label: runtimeXAxisLabel ?? newConfig.xAxis.label }
newConfig.runtime.yAxis = { ...newConfig.yAxis, label: runtimeYAxisLabel ?? newConfig.yAxis.label }
newConfig.runtime.horizontal = false
}
newConfig.runtime.uniqueId = Date.now()
// Set error messages: preserve external errors (from pattern settings, etc.) or set validation errors
if (shouldPreserveError) {
// Preserve error messages set by editor panels (e.g., pattern contrast errors)
newConfig.runtime.editorErrorMessage = existingErrorMessage
} else if (newConfig.visualizationType === 'Pie') {
// Check for Pie chart validation errors
const missingDataColumn = !newConfig.yAxis.dataKey || newConfig.yAxis.dataKey === ''
const missingSegmentLabels = !newConfig.xAxis.dataKey || newConfig.xAxis.dataKey === ''
if (missingDataColumn && missingSegmentLabels) {
newConfig.runtime.editorErrorMessage = 'Data column and Segment labels sections must be set for pie charts.'
} else if (missingDataColumn) {
newConfig.runtime.editorErrorMessage = 'Data column section must be set for pie charts.'
} else if (missingSegmentLabels) {
newConfig.runtime.editorErrorMessage = 'Segment labels section must be set for pie charts.'
} else {
newConfig.runtime.editorErrorMessage = ''
}
} else {
// No errors
newConfig.runtime.editorErrorMessage = ''
}
if (newConfig.legend.seriesHighlight?.length) {
dispatch({ type: 'SET_SERIES_HIGHLIGHT', payload: newConfig.legend?.seriesHighlight })
}
setConfig(newConfig)
}
// Sorts data series for horizontal bar charts
const sortData = (a, b) => {
let sortKey =
config.visualizationType === 'Bar' && config.visualizationSubType === 'horizontal'
? config.xAxis.dataKey
: config.yAxis.sortKey
let aData = parseFloat(a[sortKey])
let bData = parseFloat(b[sortKey])
if (aData < bData) {
return config.sortData === 'ascending' ? 1 : -1
} else if (aData > bData) {
return config.sortData === 'ascending' ? -1 : 1
} else {
return 0
}
}
const setFilters = (newFilters: VizFilter[]) => {
if (!config.dynamicSeries) {
const _newFilters = addValuesToFilters(newFilters, excludedData)
setConfig({
...config,
filters: _newFilters
})
}
if (config.filterBehavior === 'Filter Change' || config.filterBehavior === 'Apply Button') {
const newFilteredData = filterVizData(newFilters, excludedData)
dispatch({ type: 'SET_FILTERED_DATA', payload: newFilteredData })
if (config.dynamicSeries) {
const runtime = getNewRuntime(config, newFilteredData)
setConfig({
...config,
filters: newFilters,
runtime
})
}
}
}
// Observes changes to outermost container and changes viewport size in state
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
let { width, height } = entry.contentRect
const editorIsOpen = isEditor
width = editorIsOpen ? width - EDITOR_WIDTH : width
const newViewport = getViewport(width)
dispatch({ type: 'SET_VIEWPORT', payload: newViewport })
dispatch({ type: 'SET_VIZ_VIEWPORT', payload: newViewport })
if (entry.target.dataset.lollipop === 'true') {
width = width - 2.5
}
width = width
dispatch({ type: 'SET_DIMENSIONS', payload: [width, height] })
}
})
const outerContainerRef = useCallback(node => {
if (node !== null) {
resizeObserver.observe(node)
}
dispatch({ type: 'SET_CONTAINER', payload: node })
}, []) // eslint-disable-line
const prepareData = async newConfig => {
try {
const urlFilters = newConfig.filters
? newConfig.filters.filter(filter => filter.type === 'url').length > 0
? true
: false
: false
if (newConfig.dataUrl && !urlFilters) {
// handle urls with spaces in the name.
if (newConfig.dataUrl) newConfig.dataUrl = `${newConfig.dataUrl}`
let newData = await fetchRemoteData(newConfig.dataUrl)
if (newConfig.vegaConfig) {
newData = extractCoveData(updateVegaData(newConfig.vegaConfig, newData))
}
if (newData && newConfig.dataDescription) {
newData = transform.autoStandardize(newData)
newData = transform.developerStandardize(newData, newConfig.dataDescription)
}
if (newData) {
newConfig.data = newData
}
} else if (newConfig.formattedData) {
newConfig.data = newConfig.formattedData
} else if (newConfig.dataDescription) {
// For dashboard contexts, get data from datasets if config.data is undefined
let dataToProcess = newConfig.data
if (!dataToProcess && isDashboard && datasets && newConfig.dataKey) {
dataToProcess = datasets[newConfig.dataKey]?.data
}
if (dataToProcess) {
newConfig.data = transform.autoStandardize(dataToProcess)
newConfig.data = transform.developerStandardize(newConfig.data, newConfig.dataDescription)
}
}
} catch (err) {
console.error('Error on prepareData function ', err)
}
return newConfig
}
useEffect(() => {
const load = async () => {
try {
if (configObj) {
const preparedConfig = await prepareConfig(configObj)
const preppedData = await prepareData(preparedConfig)
if (preparedConfig?.formattedData?.length) {
preppedData.data = preparedConfig.formattedData
}
dispatch({ type: 'SET_STATE_DATA', payload: preppedData.data })
dispatch({ type: 'SET_EXCLUDED_DATA', payload: preppedData.data })
updateConfig(preparedConfig, preppedData.data)
}
} catch (err) {
console.error('Could not Load!')
}
}
load()
}, [configObj?.data?.length ? configObj.data : null])
/**
* When cove has a config and container ref publish the cove_loaded event.
*/
useEffect(() => {
if (container && !isLoading && !_.isEmpty(config) && !coveLoadedEventRan) {
publish('cove_loaded', { config: config })
dispatch({ type: 'SET_LOADED_EVENT', payload: true })
}
}, [container, config, isLoading]) // eslint-disable-line
/**
* Handles filter change events outside of COVE
* Updates externalFilters state
* Another useEffect listens to externalFilterChanges and updates the config.
*/
useEffect(() => {
const handleFilterData = e => {
let tmp: any[] = []
tmp.push(e.detail)
setExternalFilters(tmp)
}
subscribe('cove_filterData', e => handleFilterData(e))
return () => {
unsubscribe('cove_filterData', handleFilterData)
}
}, [config])
/**
* Handles changes to externalFilters
* For some reason e.detail is returning [order: "asc"] even though
* we're not passing that in. The code here checks for an active prop instead of an empty array.
*/
useEffect(() => {
if (externalFilters && externalFilters[0]) {
const hasActiveProperty = externalFilters[0].hasOwnProperty('active')
if (!hasActiveProperty) {
let configCopy = { ...config }
delete configCopy['filters']
setConfig(configCopy)
dispatch({ type: 'SET_FILTERED_DATA', payload: filterVizData(externalFilters, excludedData) })
}
}
if (
externalFilters &&
externalFilters.length > 0 &&
externalFilters.length > 0 &&
externalFilters[0].hasOwnProperty('active')
) {
let newConfigHere = { ...config, filters: externalFilters }
setConfig(newConfigHere)
dispatch({ type: 'SET_FILTERED_DATA', payload: filterVizData(externalFilters, excludedData) })
}
}, [externalFilters]) // eslint-disable-line
// Generates color palette to pass to child chart component
useEffect(() => {
if (stateData && config.xAxis && config.runtime?.seriesKeys) {
const newColorScale = getColorScale(config)
dispatch({ type: 'SET_COLOR_SCALE', payload: newColorScale })
// setColorScale(newColorScale)
dispatch({ type: 'SET_LOADING', payload: false })
}
if (config && stateData && config.sortData) {
stateData.sort(sortData)
}
}, [config, stateData]) // eslint-disable-line
// Updates runtime axis labels when config or data changes when using markup variables
useEffect(() => {
if (
!config?.runtime ||
_.isEmpty(config.runtime) ||
(!config.runtime.xAxis && !config.runtime.yAxis) ||
!config.markupVariables?.length
) {
return
}
const dataSource = (stateData && stateData.length ? stateData : config.data) || []
const { runtimeXAxisLabel, runtimeYAxisLabel, isHorizontalVariant } = getProcessedAxisLabels(config, dataSource)
const runtimeClone = _.cloneDeep(config.runtime)
if (!runtimeClone?.xAxis || !runtimeClone?.yAxis) {
return
}
let shouldUpdateLabels = false
if (typeof runtimeXAxisLabel !== 'undefined' && runtimeClone.xAxis.label !== runtimeXAxisLabel) {
runtimeClone.xAxis = { ...runtimeClone.xAxis, label: runtimeXAxisLabel }
shouldUpdateLabels = true
}
if (typeof runtimeYAxisLabel !== 'undefined' && runtimeClone.yAxis.label !== runtimeYAxisLabel) {
runtimeClone.yAxis = { ...runtimeClone.yAxis, label: runtimeYAxisLabel }
shouldUpdateLabels = true
}
if (shouldUpdateLabels) {
runtimeClone.uniqueId = Date.now()
const updatedConfig = { ...config, runtime: runtimeClone } as ChartConfig
dispatch({ type: 'SET_CONFIG', payload: updatedConfig })
if (isEditor && !isDashboard) {
editorContext.setTempConfig(updatedConfig)
}
}
}, [config, stateData, getProcessedAxisLabels, dispatch, editorContext, isEditor, isDashboard])
// Called on legend click, highlights/unhighlights the data series with the given label
const highlight = (label: Label): void => {
if (
seriesHighlight.length + 1 === config.runtime.seriesKeys.length &&
config.visualizationType !== 'Forecasting' &&
!seriesHighlight.includes(label.datum)
) {
return handleShowAll()
}
const newHighlight = _.findKey(config.runtime.seriesLabels, v => v === label.datum) || label.datum
const newSeriesHighlight = _.xor(seriesHighlight, [newHighlight])
dispatch({ type: 'SET_SERIES_HIGHLIGHT', payload: newSeriesHighlight })
}
// Called on reset button click, unhighlights all data series
const handleShowAll = () => {
try {
const legend = legendRef.current
if (!legend) throw new Error('No legend available to set previous focus on.')
legend.focus()
} catch (e) {
console.error('COVE:', e.message)
}
publishAnalyticsEvent({
vizType: config?.type,
vizSubType: getVizSubType(config),
eventType: 'chart_legend_reset',
eventAction: 'click',
eventLabel: interactionLabel,
vizTitle: getVizTitle(config),
...(config.visualizationType === 'Bar' && {
specifics: `orientation: ${config.orientation === 'horizontal' ? 'horizontal' : 'vertical'}`
})
})
dispatch({ type: 'SET_SERIES_HIGHLIGHT', payload: [] })
}
const section = config.orientation === 'horizontal' ? 'yAxis' : 'xAxis'
const parseDate = (dateString, showError = true) => {
let date = timeParse(config.runtime[section].dateParseFormat)(dateString)
if (!date) {
if (showError) {
config.runtime.editorErrorMessage = `Error parsing date "${dateString}". Try reviewing your data and date parse settings in the X Axis section.`
}
return new Date()
} else {
return date
}
}
const formatDate = (date, i, ticks) => {
const displayFormat =
config.runtime[section].dateDisplayFormat || config.runtime[section].dateParseFormat || '%Y-%m-%d'
let formattedDate = timeFormat(displayFormat)(date)
// Handle the case where all months work with '%b.' except for May
if (displayFormat?.includes('%b.') && formattedDate.includes('May.')) {
formattedDate = formattedDate.replace(/May\./g, 'May')
}
// Show years only once
if (config.xAxis.showYearsOnce && displayFormat?.includes('%Y') && ticks) {
const prevDate = ticks[i - 1] ? ticks[i - 1].value : null
const prevFormattedDate = timeFormat(displayFormat)(prevDate)
const year = formattedDate.match(/\d{4}/)
const prevYear = prevFormattedDate.match(/\d{4}/)
if (year && prevYear && year[0] === prevYear[0]) {
formattedDate = formattedDate.replace(year, '')
}
}
return formattedDate
}
const formatTooltipsDate = date => {
return timeFormat(config.tooltips.dateDisplayFormat)(date)
}
// Format numeric data based on settings in config OR from passed in settings for Additional Columns
// - use only for old horizontal data - newer formatNumber is in helper/formatNumber
// TODO: we should combine various formatNumber functions across this project.
// TODO suggestion: pass all options as object key/values to allow for more flexibility
const formatNumber = (
num,
axis,
shouldAbbreviate = false,
addColPrefix,
addColSuffix,
addColRoundTo,
{ index, length } = { index: null, length: null }
) => {
if (num === '') return 'N/A'
// if num is NaN return num
if (isNaN(num) || !num) return num
// Check if the input number is negative
const isNegative = num < 0
if (axis === undefined || !axis) axis = 'left'
// If the input number is negative, take the absolute value
if (isNegative) {
num = Math.abs(num)
}
// destructure dataFormat values
let {
dataFormat: {
commas,
abbreviated,
roundTo,
prefix,
suffix,
rightRoundTo,
bottomRoundTo,
rightPrefix,
rightSuffix,
bottomPrefix,
bottomSuffix,
bottomAbbreviated,
preserveOriginalDecimals
}
} = config
// check if value contains comma and remove it. later will add comma below.
if (String(num).indexOf(',') !== -1) num = num.replaceAll(',', '')
let original = num
let stringFormattingOptions: any = {
useGrouping: commas ? true : false // for old chart data table to work right cant just leave this to undefined
}
if (axis === 'left' || axis === undefined) {
let roundToPlace
if (addColRoundTo !== undefined) {
// if its an Additional Column
roundToPlace = addColRoundTo ? Number(addColRoundTo) : 0
} else {
roundToPlace = roundTo ? Number(roundTo) : 0
}
// If preserveOriginalDecimals is enabled, don't force decimal places
if (preserveOriginalDecimals) {
stringFormattingOptions = {
useGrouping: addColRoundTo ? true : config.dataFormat.commas ? true : false
}
} else {
stringFormattingOptions = {
useGrouping: addColRoundTo ? true : config.dataFormat.commas ? true : false,
minimumFractionDigits: roundToPlace,
maximumFractionDigits: roundToPlace
}
}
}
if (axis === 'right') {
if (preserveOriginalDecimals) {
stringFormattingOptions = {
useGrouping: config.dataFormat.rightCommas ? true : false
}
} else {
stringFormattingOptions = {
useGrouping: config.dataFormat.rightCommas ? true : false,
minimumFractionDigits: rightRoundTo ? Number(rightRoundTo) : 0,
maximumFractionDigits: rightRoundTo ? Number(rightRoundTo) : 0
}
}
}
const resolveBottomTickRounding = () => {
if (config.forestPlot?.type === 'Logarithmic' && !bottomRoundTo) return 2
if (Number(bottomRoundTo)) return Number(bottomRoundTo)
return 0
}
if (axis === 'bottom') {
if (preserveOriginalDecimals) {
stringFormattingOptions = {
useGrouping: config.dataFormat.bottomCommas ? true : false
}
} else {
stringFormattingOptions = {
useGrouping: config.dataFormat.bottomCommas ? true : false,
minimumFractionDigits: resolveBottomTickRounding(),
maximumFractionDigits: resolveBottomTickRounding()
}
}
}
num = numberFromString(num)
if (isNaN(num)) {
config.runtime.editorErrorMessage = `Unable to parse number from data ${original}. Try reviewing your data and selections in the Data Series section.`
return original
}
if (!config.dataFormat) return num
if (config.dataCutoff) {
let cutoff = numberFromString(config.dataCutoff)
if (num < cutoff) {
num = cutoff
}
}
// When we're formatting the left axis
// Use commas also updates bars and the data table
// We can't use commas when we're formatting the dataFormatted number
// Example: commas -> 12,000; abbreviated -> 12k (correct); abbreviated & commas -> 12 (incorrect)
//
// Edge case for small numbers with decimals
// - if roundTo undefined which means it is blank, then do not round
if (
(axis === 'left' && commas && abbreviated && shouldAbbreviate) ||
(axis === 'bottom' && commas && abbreviated && shouldAbbreviate)
) {
num = num // eslint-disable-line
} else {
num = num.toLocaleString('en-US', stringFormattingOptions)
}
let result = ''
if (abbreviated && axis === 'left' && shouldAbbreviate) {
num = abbreviateNumber(parseFloat(num))
}
if (bottomAbbreviated && axis === 'bottom' && shouldAbbreviate) {
num = abbreviateNumber(parseFloat(num))
}
if (addColPrefix && axis === 'left') {
result = addColPrefix + result