-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathGrapher.tsx
3802 lines (3285 loc) · 129 KB
/
Grapher.tsx
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 from "react"
import ReactDOMServer from "react-dom/server.js"
import {
observable,
computed,
action,
autorun,
runInAction,
reaction,
} from "mobx"
import { bind } from "decko"
import {
uniqWith,
isEqual,
uniq,
slugify,
lowerCaseFirstLetterUnlessAbbreviation,
isMobile,
next,
sampleFrom,
range,
exposeInstanceOnWindow,
findClosestTime,
excludeUndefined,
debounce,
isInIFrame,
differenceObj,
QueryParams,
MultipleOwidVariableDataDimensionsMap,
OwidVariableDataMetadataDimensions,
OwidVariableMixedData,
OwidVariableWithSourceAndDimension,
Bounds,
DEFAULT_BOUNDS,
minTimeBoundFromJSONOrNegativeInfinity,
maxTimeBoundFromJSONOrPositiveInfinity,
TimeBounds,
getTimeDomainFromQueryString,
TimeBound,
minTimeToJSON,
maxTimeToJSON,
timeBoundToTimeBoundString,
objectWithPersistablesToObject,
deleteRuntimeAndUnchangedProps,
updatePersistables,
strToQueryParams,
queryParamsToStr,
setWindowQueryStr,
getWindowUrl,
Url,
EntityYearHighlight,
ColumnSlug,
DimensionProperty,
SortBy,
SortConfig,
SortOrder,
OwidChartDimensionInterface,
firstOfNonEmptyArray,
spansToUnformattedPlainText,
EnrichedDetail,
isEmpty,
compact,
getOriginAttributionFragments,
sortBy,
extractDetailsFromSyntax,
omit,
isTouchDevice,
isArrayDifferentFromReference,
} from "@ourworldindata/utils"
import {
MarkdownTextWrap,
sumTextWrapHeights,
} from "@ourworldindata/components"
import {
GrapherChartType,
ScaleType,
StackMode,
EntitySelectionMode,
ScatterPointLabelStrategy,
RelatedQuestionsConfig,
FacetStrategy,
SeriesColorMap,
FacetAxisDomain,
AnnotationFieldsInTitle,
MissingDataStrategy,
SeriesStrategy,
GrapherInterface,
grapherKeysToSerialize,
GrapherQueryParams,
LegacyGrapherInterface,
MapProjectionName,
LogoOption,
ComparisonLineConfig,
ColumnSlugs,
Time,
EntityName,
OwidColumnDef,
OwidVariableRow,
ColorSchemeName,
AxisConfigInterface,
GrapherStaticFormat,
DetailsMarker,
DetailDictionary,
GrapherWindowType,
Color,
GRAPHER_QUERY_PARAM_KEYS,
GrapherTooltipAnchor,
GrapherTabName,
GRAPHER_CHART_TYPES,
GRAPHER_TAB_OPTIONS,
GRAPHER_TAB_NAMES,
GRAPHER_TAB_QUERY_PARAMS,
GrapherTabOption,
SeriesName,
} from "@ourworldindata/types"
import {
BlankOwidTable,
OwidTable,
ColumnTypeMap,
CoreColumn,
} from "@ourworldindata/core-table"
import {
BASE_FONT_SIZE,
CookieKey,
ThereWasAProblemLoadingThisChart,
DEFAULT_GRAPHER_WIDTH,
DEFAULT_GRAPHER_HEIGHT,
DEFAULT_GRAPHER_ENTITY_TYPE,
DEFAULT_GRAPHER_ENTITY_TYPE_PLURAL,
STATIC_EXPORT_DETAIL_SPACING,
GRAPHER_LOADED_EVENT_NAME,
isContinentsVariableId,
isPopulationVariableETLPath,
GRAPHER_FRAME_PADDING_HORIZONTAL,
GRAPHER_FRAME_PADDING_VERTICAL,
latestGrapherConfigSchema,
GRAPHER_SQUARE_SIZE,
} from "../core/GrapherConstants"
import { loadVariableDataAndMetadata } from "./loadVariable"
import Cookies from "js-cookie"
import {
ChartDimension,
LegacyDimensionsManager,
} from "../chart/ChartDimension"
import { TooltipManager } from "../tooltip/TooltipProps"
import { DimensionSlot } from "../chart/DimensionSlot"
import {
getFocusedSeriesNamesParam,
getSelectedEntityNamesParam,
} from "./EntityUrlBuilder"
import { AxisConfig, AxisManager } from "../axis/AxisConfig"
import { ColorScaleConfig } from "../color/ColorScaleConfig"
import { MapConfig } from "../mapCharts/MapConfig"
import { FullScreen } from "../fullScreen/FullScreen"
import { isOnTheMap } from "../mapCharts/EntitiesOnTheMap"
import { ChartManager } from "../chart/ChartManager"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome/index.js"
import { faExclamationTriangle } from "@fortawesome/free-solid-svg-icons"
import { SettingsMenuManager } from "../controls/SettingsMenu"
import { TooltipContainer } from "../tooltip/Tooltip"
import {
EntitySelectorModal,
EntitySelectorModalManager,
} from "../modal/EntitySelectorModal"
import { DownloadModal, DownloadModalManager } from "../modal/DownloadModal"
import ReactDOM from "react-dom"
import { observer } from "mobx-react"
import "d3-transition"
import { SourcesModal, SourcesModalManager } from "../modal/SourcesModal"
import { DataTableManager } from "../dataTable/DataTable"
import { MapChartManager } from "../mapCharts/MapChartConstants"
import { MapChart } from "../mapCharts/MapChart"
import { DiscreteBarChartManager } from "../barCharts/DiscreteBarChartConstants"
import { Command, CommandPalette } from "../controls/CommandPalette"
import { ShareMenuManager } from "../controls/ShareMenu"
import { EmbedModalManager, EmbedModal } from "../modal/EmbedModal"
import {
CaptionedChart,
CaptionedChartManager,
StaticCaptionedChart,
} from "../captionedChart/CaptionedChart"
import {
TimelineController,
TimelineManager,
} from "../timeline/TimelineController"
import Mousetrap from "mousetrap"
import { SlideShowController } from "../slideshowController/SlideShowController"
import {
ChartComponentClassMap,
DefaultChartClass,
} from "../chart/ChartTypeMap"
import { Entity, SelectionArray } from "../selection/SelectionArray"
import { legacyToOwidTableAndDimensions } from "./LegacyToOwidTable"
import { ScatterPlotManager } from "../scatterCharts/ScatterPlotChartConstants"
import {
autoDetectSeriesStrategy,
autoDetectYColumnSlugs,
findValidChartTypeCombination,
mapChartTypeNameToQueryParam,
mapQueryParamToChartTypeName,
} from "../chart/ChartUtils"
import classnames from "classnames"
import { GrapherAnalytics } from "./GrapherAnalytics"
import { legacyToCurrentGrapherQueryParams } from "./GrapherUrlMigrations"
import { ChartInterface, ChartTableTransformer } from "../chart/ChartInterface"
import { MarimekkoChartManager } from "../stackedCharts/MarimekkoChartConstants"
import Bugsnag from "@bugsnag/js"
import { FacetChartManager } from "../facetChart/FacetChartConstants"
import {
StaticChartRasterizer,
type GrapherExport,
} from "../captionedChart/StaticChartRasterizer.js"
import { SlopeChartManager } from "../slopeCharts/SlopeChart"
import { SidePanel } from "../sidePanel/SidePanel"
import {
EntitySelector,
type EntitySelectorState,
} from "../entitySelector/EntitySelector"
import { SlideInDrawer } from "../slideInDrawer/SlideInDrawer"
import { BodyDiv } from "../bodyDiv/BodyDiv"
import { grapherObjectToQueryParams } from "./GrapherUrl.js"
import { FocusArray } from "../focus/FocusArray"
import {
GRAPHER_BACKGROUND_BEIGE,
GRAPHER_BACKGROUND_DEFAULT,
GRAPHER_DARK_TEXT,
GRAPHER_LIGHT_TEXT,
} from "../color/ColorConstants"
import { FacetChart } from "../facetChart/FacetChart"
declare global {
interface Window {
details?: DetailDictionary
admin?: any // TODO: use stricter type
}
}
async function loadVariablesDataAdmin(
variableFetchBaseUrl: string | undefined,
variableIds: number[]
): Promise<MultipleOwidVariableDataDimensionsMap> {
const dataFetchPath = (variableId: number): string =>
variableFetchBaseUrl
? `${variableFetchBaseUrl}/v1/variableById/data/${variableId}`
: `/api/data/variables/data/${variableId}.json`
const metadataFetchPath = (variableId: number): string =>
variableFetchBaseUrl
? `${variableFetchBaseUrl}/v1/variableById/metadata/${variableId}`
: `/api/data/variables/metadata/${variableId}.json`
const loadVariableDataPromises = variableIds.map(async (variableId) => {
const dataPromise = window.admin.getJSON(
dataFetchPath(variableId)
) as Promise<OwidVariableMixedData>
const metadataPromise = window.admin.getJSON(
metadataFetchPath(variableId)
) as Promise<OwidVariableWithSourceAndDimension>
const [data, metadata] = await Promise.all([
dataPromise,
metadataPromise,
])
return { data, metadata: { ...metadata, id: variableId } }
})
const variablesData: OwidVariableDataMetadataDimensions[] =
await Promise.all(loadVariableDataPromises)
const variablesDataMap = new Map(
variablesData.map((data) => [data.metadata.id, data])
)
return variablesDataMap
}
async function loadVariablesDataSite(
variableIds: number[],
dataApiUrl: string
): Promise<MultipleOwidVariableDataDimensionsMap> {
const loadVariableDataPromises = variableIds.map((variableId) =>
loadVariableDataAndMetadata(variableId, dataApiUrl)
)
const variablesData: OwidVariableDataMetadataDimensions[] =
await Promise.all(loadVariableDataPromises)
const variablesDataMap = new Map(
variablesData.map((data) => [data.metadata.id, data])
)
return variablesDataMap
}
const DEFAULT_MS_PER_TICK = 100
// Exactly the same as GrapherInterface, but contains options that developers want but authors won't be touching.
export interface GrapherProgrammaticInterface extends GrapherInterface {
owidDataset?: MultipleOwidVariableDataDimensionsMap // This is temporarily used for testing. Will be removed
manuallyProvideData?: boolean // This will be removed.
queryStr?: string
bounds?: Bounds
table?: OwidTable
bakedGrapherURL?: string
adminBaseUrl?: string
dataApiUrl?: string
env?: string
dataApiUrlForAdmin?: string
entityYearHighlight?: EntityYearHighlight
baseFontSize?: number
staticBounds?: Bounds
staticFormat?: GrapherStaticFormat
hideTitle?: boolean
hideSubtitle?: boolean
hideNote?: boolean
hideOriginUrl?: boolean
hideEntityControls?: boolean
hideZoomToggle?: boolean
hideNoDataAreaToggle?: boolean
hideFacetYDomainToggle?: boolean
hideXScaleToggle?: boolean
hideYScaleToggle?: boolean
hideMapProjectionMenu?: boolean
hideTableFilterToggle?: boolean
forceHideAnnotationFieldsInTitle?: AnnotationFieldsInTitle
hasTableTab?: boolean
hideChartTabs?: boolean
hideShareButton?: boolean
hideExploreTheDataButton?: boolean
hideRelatedQuestion?: boolean
isSocialMediaExport?: boolean
getGrapherInstance?: (instance: Grapher) => void
enableKeyboardShortcuts?: boolean
bindUrlToWindow?: boolean
isEmbeddedInAnOwidPage?: boolean
isEmbeddedInADataPage?: boolean
manager?: GrapherManager
instanceRef?: React.RefObject<Grapher>
}
export interface GrapherManager {
canonicalUrl?: string
embedDialogUrl?: string
embedDialogAdditionalElements?: React.ReactElement
selection?: SelectionArray
focusArray?: FocusArray
editUrl?: string
}
@observer
export class Grapher
extends React.Component<GrapherProgrammaticInterface>
implements
TimelineManager,
ChartManager,
AxisManager,
CaptionedChartManager,
SourcesModalManager,
DownloadModalManager,
DiscreteBarChartManager,
LegacyDimensionsManager,
ShareMenuManager,
EmbedModalManager,
TooltipManager,
DataTableManager,
ScatterPlotManager,
MarimekkoChartManager,
FacetChartManager,
EntitySelectorModalManager,
SettingsMenuManager,
MapChartManager,
SlopeChartManager
{
@observable.ref $schema = latestGrapherConfigSchema
@observable.ref chartTypes: GrapherChartType[] = [
GRAPHER_CHART_TYPES.LineChart,
]
@observable.ref id?: number = undefined
@observable.ref version = 1
@observable.ref slug?: string = undefined
// Initializing text fields with `undefined` ensures that empty strings get serialised
@observable.ref title?: string = undefined
@observable.ref subtitle: string | undefined = undefined
@observable.ref sourceDesc?: string = undefined
@observable.ref note?: string = undefined
@observable.ref variantName?: string = undefined
@observable.ref internalNotes?: string = undefined
@observable.ref originUrl?: string = undefined
@observable hideAnnotationFieldsInTitle?: AnnotationFieldsInTitle =
undefined
@observable.ref minTime?: TimeBound = undefined
@observable.ref maxTime?: TimeBound = undefined
@observable.ref timelineMinTime?: Time = undefined
@observable.ref timelineMaxTime?: Time = undefined
@observable.ref addCountryMode = EntitySelectionMode.MultipleEntities
@observable.ref stackMode = StackMode.absolute
@observable.ref showNoDataArea = true
@observable.ref hideLegend?: boolean = false
@observable.ref logo?: LogoOption = undefined
@observable.ref hideLogo?: boolean = undefined
@observable.ref hideRelativeToggle? = true
@observable.ref entityType = DEFAULT_GRAPHER_ENTITY_TYPE
@observable.ref entityTypePlural = DEFAULT_GRAPHER_ENTITY_TYPE_PLURAL
@observable.ref facettingLabelByYVariables = "metric"
@observable.ref hideTimeline?: boolean = undefined
@observable.ref hideScatterLabels?: boolean = undefined
@observable.ref zoomToSelection?: boolean = undefined
@observable.ref showYearLabels?: boolean = undefined // Always show year in labels for bar charts
@observable.ref hasMapTab = false
@observable.ref tab: GrapherTabOption = GRAPHER_TAB_OPTIONS.chart
@observable.ref chartTab?: GrapherChartType
@observable.ref isPublished?: boolean = undefined
@observable.ref baseColorScheme?: ColorSchemeName = undefined
@observable.ref invertColorScheme?: boolean = undefined
@observable hideConnectedScatterLines?: boolean = undefined // Hides lines between points when timeline spans multiple years. Requested by core-econ for certain charts
@observable
scatterPointLabelStrategy?: ScatterPointLabelStrategy = undefined
@observable.ref compareEndPointsOnly?: boolean = undefined
@observable.ref matchingEntitiesOnly?: boolean = undefined
/** Hides the total value label that is normally displayed for stacked bar charts */
@observable.ref hideTotalValueLabel?: boolean = undefined
@observable.ref missingDataStrategy?: MissingDataStrategy = undefined
@observable.ref showSelectionOnlyInDataTable?: boolean = undefined
@observable.ref xAxis = new AxisConfig(undefined, this)
@observable.ref yAxis = new AxisConfig(undefined, this)
@observable colorScale = new ColorScaleConfig()
@observable map = new MapConfig()
@observable.ref dimensions: ChartDimension[] = []
@observable ySlugs?: ColumnSlugs = undefined
@observable xSlug?: ColumnSlug = undefined
@observable colorSlug?: ColumnSlug = undefined
@observable sizeSlug?: ColumnSlug = undefined
@observable tableSlugs?: ColumnSlugs = undefined
@observable selectedEntityColors: {
[entityName: string]: string | undefined
} = {}
@observable selectedEntityNames: EntityName[] = []
@observable focusedSeriesNames: SeriesName[] = []
@observable excludedEntities?: number[] = undefined
/** IncludedEntities are usually empty which means use all available entities. When
includedEntities is set it means "only use these entities". excludedEntities
are evaluated afterwards and can still remove entities even if they were included before.
*/
@observable includedEntities?: number[] = undefined
@observable comparisonLines?: ComparisonLineConfig[] = undefined // todo: Persistables?
@observable relatedQuestions?: RelatedQuestionsConfig[] = undefined // todo: Persistables?
/**
* Used to highlight an entity at a particular time in a line chart.
* The sparkline in map tooltips makes use of this.
*/
@observable.ref entityYearHighlight?: EntityYearHighlight = undefined
@observable.ref hideFacetControl?: boolean = undefined
// the desired faceting strategy, which might not be possible if we change the data
@observable selectedFacetStrategy?: FacetStrategy = undefined
@observable sortBy?: SortBy = SortBy.total
@observable sortOrder?: SortOrder = SortOrder.desc
@observable sortColumnSlug?: string
@observable.ref _isInFullScreenMode = false
@observable.ref windowInnerWidth?: number
@observable.ref windowInnerHeight?: number
owidDataset?: MultipleOwidVariableDataDimensionsMap = undefined // This is used for passing data for testing
manuallyProvideData? = false // This will be removed.
// TODO: Pass these 5 in as options, don't get them as globals.
isDev = this.props.env === "development"
analytics = new GrapherAnalytics(this.props.env ?? "")
isEditor =
typeof window !== "undefined" && (window as any).isEditor === true
@observable bakedGrapherURL = this.props.bakedGrapherURL
adminBaseUrl = this.props.adminBaseUrl
dataApiUrl =
this.props.dataApiUrl ?? "https://api.ourworldindata.org/v1/indicators/"
@observable.ref externalQueryParams: QueryParams
private framePaddingHorizontal = GRAPHER_FRAME_PADDING_HORIZONTAL
private framePaddingVertical = GRAPHER_FRAME_PADDING_VERTICAL
@observable.ref inputTable: OwidTable
@observable.ref legacyConfigAsAuthored: Partial<LegacyGrapherInterface> = {}
// stored on Grapher so state is preserved when switching to full-screen mode
@observable entitySelectorState: Partial<EntitySelectorState> = {}
@computed get dataApiUrlForAdmin(): string | undefined {
return this.props.dataApiUrlForAdmin
}
@computed get dataTableSlugs(): ColumnSlug[] {
return this.tableSlugs ? this.tableSlugs.split(" ") : this.newSlugs
}
isEmbeddedInAnOwidPage?: boolean = this.props.isEmbeddedInAnOwidPage
isEmbeddedInADataPage?: boolean = this.props.isEmbeddedInADataPage
selection =
this.manager?.selection ??
new SelectionArray(
this.props.selectedEntityNames ?? [],
this.props.table?.availableEntities ?? []
)
focusArray = this.manager?.focusArray ?? new FocusArray()
/**
* todo: factor this out and make more RAII.
*
* Explorers create 1 Grapher instance, but as the user clicks around the Explorer loads other author created Graphers.
* But currently some Grapher features depend on knowing how the current state is different than the "authored state".
* So when an Explorer updates the grapher, it also needs to update this "original state".
*/
@action.bound setAuthoredVersion(
config: Partial<LegacyGrapherInterface>
): void {
this.legacyConfigAsAuthored = config
}
@action.bound updateAuthoredVersion(
config: Partial<LegacyGrapherInterface>
): void {
this.legacyConfigAsAuthored = {
...this.legacyConfigAsAuthored,
...config,
}
}
constructor(
propsWithGrapherInstanceGetter: GrapherProgrammaticInterface = {}
) {
super(propsWithGrapherInstanceGetter)
const { getGrapherInstance, ...props } = propsWithGrapherInstanceGetter
this.inputTable = props.table ?? BlankOwidTable(`initialGrapherTable`)
if (props) this.setAuthoredVersion(props)
// prefer the manager's selection over the config's selectedEntityNames
// if both are passed in and the manager's selection is not empty.
// this is necessary for the global entity selector to work correctly.
if (props.manager?.selection?.hasSelection) {
this.updateFromObject(omit(props, "selectedEntityNames"))
} else {
this.updateFromObject(props)
}
if (!props.table) this.downloadData()
this.populateFromQueryParams(
legacyToCurrentGrapherQueryParams(props.queryStr ?? "")
)
this.externalQueryParams = omit(
Url.fromQueryStr(props.queryStr ?? "").queryParams,
GRAPHER_QUERY_PARAM_KEYS
)
if (this.isEditor) {
this.ensureValidConfigWhenEditing()
}
if (getGrapherInstance) getGrapherInstance(this) // todo: possibly replace with more idiomatic ref
}
toObject(): GrapherInterface {
const obj: GrapherInterface = objectWithPersistablesToObject(
this,
grapherKeysToSerialize
)
obj.selectedEntityNames = this.selection.selectedEntityNames
obj.focusedSeriesNames = this.focusArray.seriesNames
deleteRuntimeAndUnchangedProps(obj, defaultObject)
// always include the schema, even if it's the default
obj.$schema = this.$schema || latestGrapherConfigSchema
// JSON doesn't support Infinity, so we use strings instead.
if (obj.minTime) obj.minTime = minTimeToJSON(this.minTime) as any
if (obj.maxTime) obj.maxTime = maxTimeToJSON(this.maxTime) as any
if (obj.timelineMinTime)
obj.timelineMinTime = minTimeToJSON(this.timelineMinTime) as any
if (obj.timelineMaxTime)
obj.timelineMaxTime = maxTimeToJSON(this.timelineMaxTime) as any
// todo: remove dimensions concept
// if (this.legacyConfigAsAuthored?.dimensions)
// obj.dimensions = this.legacyConfigAsAuthored.dimensions
return obj
}
@action.bound downloadData(): void {
if (this.manuallyProvideData) {
// ignore
} else if (this.owidDataset) {
this._receiveOwidDataAndApplySelection(this.owidDataset)
} else void this.downloadLegacyDataFromOwidVariableIds()
}
@action.bound updateFromObject(obj?: GrapherProgrammaticInterface): void {
if (!obj) return
updatePersistables(this, obj)
// Regression fix: some legacies have this set to Null. Todo: clean DB.
if (obj.originUrl === null) this.originUrl = ""
// update selection
if (obj.selectedEntityNames)
this.selection.setSelectedEntities(obj.selectedEntityNames)
// update focus
if (obj.focusedSeriesNames)
this.focusArray.clearAllAndAdd(...obj.focusedSeriesNames)
// JSON doesn't support Infinity, so we use strings instead.
this.minTime = minTimeBoundFromJSONOrNegativeInfinity(obj.minTime)
this.maxTime = maxTimeBoundFromJSONOrPositiveInfinity(obj.maxTime)
this.timelineMinTime = minTimeBoundFromJSONOrNegativeInfinity(
obj.timelineMinTime
)
this.timelineMaxTime = maxTimeBoundFromJSONOrPositiveInfinity(
obj.timelineMaxTime
)
// Todo: remove once we are more RAII.
if (obj?.dimensions?.length)
this.setDimensionsFromConfigs(obj.dimensions)
}
@action.bound populateFromQueryParams(params: GrapherQueryParams): void {
// Set tab if specified
if (params.tab) {
const tab = this.mapQueryParamToGrapherTab(params.tab)
if (tab) this.setTab(tab)
else console.error("Unexpected tab: " + params.tab)
}
// Set overlay if specified
const overlay = params.overlay
if (overlay) {
if (overlay === "sources") {
this.isSourcesModalOpen = true
} else if (overlay === "download") {
this.isDownloadModalOpen = true
} else {
console.error("Unexpected overlay: " + overlay)
}
}
// Stack mode for bar and stacked area charts
this.stackMode = (params.stackMode ?? this.stackMode) as StackMode
this.zoomToSelection =
params.zoomToSelection === "true" ? true : this.zoomToSelection
// Axis scale mode
const xScaleType = params.xScale
if (xScaleType) {
if (xScaleType === ScaleType.linear || xScaleType === ScaleType.log)
this.xAxis.scaleType = xScaleType
else console.error("Unexpected xScale: " + xScaleType)
}
const yScaleType = params.yScale
if (yScaleType) {
if (yScaleType === ScaleType.linear || yScaleType === ScaleType.log)
this.yAxis.scaleType = yScaleType
else console.error("Unexpected xScale: " + yScaleType)
}
const time = params.time
if (time !== undefined && time !== "")
this.setTimeFromTimeQueryParam(time)
const endpointsOnly = params.endpointsOnly
if (endpointsOnly !== undefined)
this.compareEndPointsOnly = endpointsOnly === "1" ? true : undefined
const region = params.region
if (region !== undefined)
this.map.projection = region as MapProjectionName
// selection
const selection = getSelectedEntityNamesParam(
Url.fromQueryParams(params)
)
if (this.addCountryMode !== EntitySelectionMode.Disabled && selection)
this.selection.setSelectedEntities(selection)
// focus
const focusedSeriesNames = getFocusedSeriesNamesParam(params.focus)
if (focusedSeriesNames) {
this.focusArray.clearAllAndAdd(...focusedSeriesNames)
}
// faceting
if (params.facet && params.facet in FacetStrategy) {
this.selectedFacetStrategy = params.facet as FacetStrategy
}
if (params.uniformYAxis === "0") {
this.yAxis.facetDomain = FacetAxisDomain.independent
} else if (params.uniformYAxis === "1") {
this.yAxis.facetDomain = FacetAxisDomain.shared
}
// only relevant for the table
if (params.showSelectionOnlyInTable) {
this.showSelectionOnlyInDataTable =
params.showSelectionOnlyInTable === "1" ? true : undefined
}
if (params.showNoDataArea) {
this.showNoDataArea = params.showNoDataArea === "1"
}
}
@action.bound private setTimeFromTimeQueryParam(time: string): void {
this.timelineHandleTimeBounds = getTimeDomainFromQueryString(time).map(
(time) => findClosestTime(this.times, time) ?? time
) as TimeBounds
}
@computed get activeTab(): GrapherTabName {
if (this.tab === GRAPHER_TAB_OPTIONS.table)
return GRAPHER_TAB_NAMES.Table
if (this.tab === GRAPHER_TAB_OPTIONS.map)
return GRAPHER_TAB_NAMES.WorldMap
if (this.chartTab) return this.chartTab
return this.chartType ?? GRAPHER_TAB_NAMES.LineChart
}
@computed get activeChartType(): GrapherChartType | undefined {
if (!this.isOnChartTab) return undefined
return this.activeTab as GrapherChartType
}
@computed get chartType(): GrapherChartType | undefined {
return this.validChartTypes[0]
}
@computed get hasChartTab(): boolean {
return this.validChartTypes.length > 0
}
@computed get isOnChartTab(): boolean {
return this.tab === GRAPHER_TAB_OPTIONS.chart
}
@computed get isOnMapTab(): boolean {
return this.tab === GRAPHER_TAB_OPTIONS.map
}
@computed get isOnTableTab(): boolean {
return this.tab === GRAPHER_TAB_OPTIONS.table
}
@computed get isOnChartOrMapTab(): boolean {
return this.isOnChartTab || this.isOnMapTab
}
@computed get yAxisConfig(): Readonly<AxisConfigInterface> {
return this.yAxis.toObject()
}
@computed get xAxisConfig(): Readonly<AxisConfigInterface> {
return this.xAxis.toObject()
}
@computed get showLegend(): boolean {
// hide the legend for stacked bar charts
// if the legend only ever shows a single entity
if (this.isOnStackedBarTab) {
const seriesStrategy =
this.chartInstance.seriesStrategy ||
autoDetectSeriesStrategy(this, true)
const isEntityStrategy = seriesStrategy === SeriesStrategy.entity
const hasSingleEntity = this.selection.numSelectedEntities === 1
const hideLegend =
this.hideLegend || (isEntityStrategy && hasSingleEntity)
return !hideLegend
}
return !this.hideLegend
}
// table that is used for display in the table tab
@computed get tableForDisplay(): OwidTable {
const table = this.table
if (!this.isReady || !this.isOnTableTab) return table
return this.chartInstance.transformTableForDisplay
? this.chartInstance.transformTableForDisplay(table)
: table
}
@computed get tableForSelection(): OwidTable {
// This table specifies which entities can be selected in the charts EntitySelectorModal.
// It should contain all entities that can be selected, and none more.
// Depending on the chart type, the criteria for being able to select an entity are
// different; e.g. for scatterplots, the entity needs to (1) not be excluded and
// (2) needs to have data for the x and y dimension.
let table = this.isScatter
? this.tableAfterAuthorTimelineAndActiveChartTransform
: this.inputTable
if (!this.isReady) return table
// Some chart types (e.g. stacked area charts) choose not to show an entity
// with incomplete data. Such chart types define a custom transform function
// to ensure that the entity selector only offers entities that are actually plotted.
if (this.chartInstance.transformTableForSelection) {
table = this.chartInstance.transformTableForSelection(table)
}
return table
}
/**
* Input table with color and size tolerance applied.
*
* This happens _before_ applying the author's timeline filter to avoid
* accidentally dropping all color values before applying tolerance.
* This is especially important for scatter plots and Marimekko charts,
* where color and size columns are often transformed with infinite tolerance.
*
* Line and discrete bar charts also support a color dimension, but their
* tolerance transformations run in their respective transformTable functions
* since it's more efficient to run them on a table that has been filtered
* by selected entities.
*/
@computed get tableAfterColorAndSizeToleranceApplication(): OwidTable {
let table = this.inputTable
if (this.isScatter && this.sizeColumnSlug) {
const tolerance =
table.get(this.sizeColumnSlug)?.display?.tolerance ?? Infinity
table = table.interpolateColumnWithTolerance(
this.sizeColumnSlug,
tolerance
)
}
if ((this.isScatter || this.isMarimekko) && this.colorColumnSlug) {
const tolerance =
table.get(this.colorColumnSlug)?.display?.tolerance ?? Infinity
table = table.interpolateColumnWithTolerance(
this.colorColumnSlug,
tolerance
)
}
return table
}
// If an author sets a timeline filter run it early in the pipeline so to the charts it's as if the filtered times do not exist
@computed get tableAfterAuthorTimelineFilter(): OwidTable {
const table = this.tableAfterColorAndSizeToleranceApplication
if (
this.timelineMinTime === undefined &&
this.timelineMaxTime === undefined
)
return table
return table.filterByTimeRange(
this.timelineMinTime ?? -Infinity,
this.timelineMaxTime ?? Infinity
)
}
// Convenience method for debugging
windowQueryParams(str = location.search): QueryParams {
return strToQueryParams(str)
}
@computed
get tableAfterAuthorTimelineAndActiveChartTransform(): OwidTable {
const table = this.tableAfterAuthorTimelineFilter
if (!this.isReady || !this.isOnChartOrMapTab) return table
const startMark = performance.now()
const transformedTable = this.chartInstance.transformTable(table)
this.createPerformanceMeasurement(
"chartInstance.transformTable",
startMark
)
return transformedTable
}
@computed get chartInstance(): ChartInterface {
// Note: when timeline handles on a LineChart are collapsed into a single handle, the
// LineChart turns into a DiscreteBar.
return this.isOnMapTab
? new MapChart({ manager: this })
: this.chartInstanceExceptMap
}
// When Map becomes a first-class chart instance, we should drop this
@computed get chartInstanceExceptMap(): ChartInterface {
const chartTypeName =
this.typeExceptWhenLineChartAndSingleTimeThenWillBeBarChart
const ChartClass =
ChartComponentClassMap.get(chartTypeName) ?? DefaultChartClass
return new ChartClass({ manager: this })
}
@computed get chartSeriesNames(): SeriesName[] {
if (!this.isReady) return []
// collect series names from all chart instances when faceted
if (this.isFaceted) {
const facetChartInstance = new FacetChart({ manager: this })
return uniq(
facetChartInstance.intermediateChartInstances.flatMap(
(chartInstance) =>
chartInstance.series.map((series) => series.seriesName)
)
)
}
return this.chartInstance.series.map((series) => series.seriesName)
}
@computed get table(): OwidTable {
return this.tableAfterAuthorTimelineFilter
}
@computed
private get tableAfterAllTransformsAndFilters(): OwidTable {
const { startTime, endTime } = this
const table = this.tableAfterAuthorTimelineAndActiveChartTransform
if (startTime === undefined || endTime === undefined) return table
if (this.isOnMapTab)
return table.filterByTargetTimes(
[endTime],
this.map.timeTolerance ??
table.get(this.mapColumnSlug).tolerance
)
if (
this.isDiscreteBar ||
this.isLineChartThatTurnedIntoDiscreteBar ||
this.isMarimekko
)
return table.filterByTargetTimes(
[endTime],
table.get(this.yColumnSlugs[0]).tolerance
)
if (this.isOnSlopeChartTab)
return table.filterByTargetTimes(
[startTime, endTime],
table.get(this.yColumnSlugs[0]).tolerance
)
return table.filterByTimeRange(startTime, endTime)
}
@computed get transformedTable(): OwidTable {
return this.tableAfterAllTransformsAndFilters
}
@observable.ref renderToStatic = false
@observable.ref isExportingToSvgOrPng = false
@observable.ref isSocialMediaExport = false
tooltip?: TooltipManager["tooltip"] = observable.box(undefined, {
deep: false,
})
@observable.ref isPlaying = false
@observable.ref isTimelineAnimationActive = false // true if the timeline animation is either playing or paused but not finished
@observable.ref animationStartTime?: Time
@observable.ref areHandlesOnSameTimeBeforeAnimation?: boolean
@observable.ref isEntitySelectorModalOrDrawerOpen = false
@observable.ref isSourcesModalOpen = false
@observable.ref isDownloadModalOpen = false