forked from owid/owid-grapher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExplorer.tsx
1167 lines (1031 loc) · 40.9 KB
/
Explorer.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 { faChartLine } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome/index.js"
import {
ColumnTypeNames,
CoreColumnDef,
OwidColumnDef,
SortOrder,
TableSlug,
GrapherInterface,
GrapherQueryParams,
GrapherTabOption,
} from "@ourworldindata/types"
import {
OwidTable,
BlankOwidTable,
extractPotentialDataSlugsFromTransform,
} from "@ourworldindata/core-table"
import {
EntityPicker,
EntityPickerManager,
Grapher,
GrapherManager,
GrapherProgrammaticInterface,
SelectionArray,
setSelectedEntityNamesParam,
SlideShowController,
SlideShowManager,
DEFAULT_GRAPHER_ENTITY_TYPE,
} from "@ourworldindata/grapher"
import {
Bounds,
ColumnSlug,
debounce,
DEFAULT_BOUNDS,
DimensionProperty,
excludeUndefined,
exposeInstanceOnWindow,
identity,
isInIFrame,
keyBy,
keyMap,
omitUndefinedValues,
parseIntOrUndefined,
PromiseCache,
PromiseSwitcher,
SerializedGridProgram,
setWindowUrl,
Tippy,
uniq,
uniqBy,
Url,
} from "@ourworldindata/utils"
import { MarkdownTextWrap, Checkbox } from "@ourworldindata/components"
import classNames from "classnames"
import { action, computed, observable, reaction } from "mobx"
import { observer } from "mobx-react"
import React, { useCallback, useEffect, useState } from "react"
import ReactDOM from "react-dom"
import { ExplorerControlBar, ExplorerControlPanel } from "./ExplorerControls.js"
import { ExplorerProgram } from "./ExplorerProgram.js"
import {
ADMIN_BASE_URL,
BAKED_BASE_URL,
BAKED_GRAPHER_URL,
DATA_API_URL,
} from "../settings/clientSettings.js"
import {
ExplorerChartCreationMode,
ExplorerChoiceParams,
ExplorerContainerId,
ExplorerFullQueryParams,
EXPLORERS_PREVIEW_ROUTE,
EXPLORERS_ROUTE_FOLDER,
UNSAVED_EXPLORER_DRAFT,
UNSAVED_EXPLORER_PREVIEW_QUERYPARAMS,
} from "./ExplorerConstants.js"
import { ExplorerPageUrlMigrationSpec } from "./urlMigrations/ExplorerPageUrlMigrationSpec.js"
import {
explorerUrlMigrationsById,
migrateExplorerUrl,
} from "./urlMigrations/ExplorerUrlMigrations.js"
import Bugsnag from "@bugsnag/js"
export interface ExplorerProps extends SerializedGridProgram {
grapherConfigs?: GrapherInterface[]
partialGrapherConfigs?: GrapherInterface[]
queryStr?: string
isEmbeddedInAnOwidPage?: boolean
isInStandalonePage?: boolean
isPreview?: boolean
canonicalUrl?: string
selection?: SelectionArray
}
const LivePreviewComponent = (props: ExplorerProps) => {
const [useLocalStorage, setUseLocalStorage] = useState(true)
const [renderedProgram, setRenderedProgram] = useState("")
const [hasLocalStorage, setHasLocalStorage] = useState(false)
const updateProgram = useCallback(() => {
const localStorageProgram = localStorage.getItem(
UNSAVED_EXPLORER_DRAFT + props.slug
)
let program: string
if (useLocalStorage) program = localStorageProgram ?? props.program
else program = props.program
setHasLocalStorage(!!localStorageProgram)
setRenderedProgram((previousProgram) => {
if (program === previousProgram) return previousProgram
return program
})
}, [props.program, props.slug, useLocalStorage])
useEffect(() => {
updateProgram()
const interval = setInterval(updateProgram, 1000)
return () => clearInterval(interval)
}, [updateProgram])
const newProps = { ...props, program: renderedProgram }
return (
<>
{hasLocalStorage && (
<div className="admin-only-locally-edited-checkbox">
<Tippy
content={
<span>
<p>
<b>Checked</b>: Use the explorer version
with changes as present in the admin.
</p>
<p>
<b>Unchecked</b>: Use the currently-saved
version.
</p>
<hr />
<p>
Note that some features may only work
correctly when this checkbox is unchecked:
in particular, using <kbd>catalogPath</kbd>s
and <kbd>grapherId</kbd>s and variable IDs.
</p>
</span>
}
placement="bottom"
>
<label>
<input
type="checkbox"
id="useLocalStorage"
onChange={(e) =>
setUseLocalStorage(e.target.checked)
}
checked={useLocalStorage}
/>
Display locally edited explorer
</label>
</Tippy>
</div>
)}
<Explorer
{...newProps}
queryStr={window.location.search}
key={Date.now()}
isPreview={true}
/>
</>
)
}
const renderLivePreviewVersion = (props: ExplorerProps) => {
ReactDOM.render(
<LivePreviewComponent {...props} />,
document.getElementById(ExplorerContainerId)
)
}
const isNarrow = () =>
window.screen.width < 450 || document.documentElement.clientWidth <= 800
@observer
export class Explorer
extends React.Component<ExplorerProps>
implements
SlideShowManager<ExplorerChoiceParams>,
EntityPickerManager,
GrapherManager
{
// caution: do a ctrl+f to find untyped usages
static renderSingleExplorerOnExplorerPage(
program: ExplorerProps,
grapherConfigs: GrapherInterface[],
partialGrapherConfigs: GrapherInterface[],
urlMigrationSpec?: ExplorerPageUrlMigrationSpec
) {
const props: ExplorerProps = {
...program,
grapherConfigs,
partialGrapherConfigs,
isEmbeddedInAnOwidPage: false,
isInStandalonePage: true,
}
if (window.location.href.includes(EXPLORERS_PREVIEW_ROUTE)) {
renderLivePreviewVersion(props)
return
}
let url = Url.fromURL(window.location.href)
// Handle redirect spec that's baked on the page.
// e.g. the old COVID Grapher to Explorer redirects are implemented this way.
if (urlMigrationSpec) {
const { explorerUrlMigrationId, baseQueryStr } = urlMigrationSpec
const migration = explorerUrlMigrationsById[explorerUrlMigrationId]
if (migration) {
url = migration.migrateUrl(url, baseQueryStr)
} else {
console.error(
`No explorer URL migration with id ${explorerUrlMigrationId}`
)
}
}
// Handle explorer-specific migrations.
// This is how we migrate the old CO2 explorer to the new CO2 explorer.
// Because they are on the same path, we can't handle it like we handle
// the COVID explorer redirects above.
url = migrateExplorerUrl(url)
// Update the window URL
setWindowUrl(url)
ReactDOM.render(
<Explorer {...props} queryStr={url.queryStr} />,
document.getElementById(ExplorerContainerId)
)
}
private initialQueryParams = Url.fromQueryStr(this.props.queryStr ?? "")
.queryParams as ExplorerFullQueryParams
explorerProgram = ExplorerProgram.fromJson(this.props).initDecisionMatrix(
this.initialQueryParams
)
// only used for the checkbox at the bottom of the embed dialog
@observable embedDialogHideControls = true
selection = this.props.selection?.hasSelection
? this.props.selection
: new SelectionArray(this.explorerProgram.selection)
entityType = this.explorerProgram.entityType ?? DEFAULT_GRAPHER_ENTITY_TYPE
@observable.ref grapher?: Grapher
@action.bound setGrapher(grapher: Grapher) {
this.grapher = grapher
}
@computed get grapherConfigs() {
const arr = this.props.grapherConfigs || []
return new Map(arr.map((config) => [config.id!, config]))
}
@computed get partialGrapherConfigsByVariableId() {
const arr = this.props.partialGrapherConfigs || []
return new Map(arr.map((config) => [config.id!, config]))
}
disposers: (() => void)[] = []
componentDidMount() {
this.setGrapher(this.grapherRef!.current!)
this.updateGrapherFromExplorer()
let url = Url.fromQueryParams(this.initialQueryParams)
if (this.props.selection?.hasSelection) {
url = setSelectedEntityNamesParam(
url,
this.props.selection.selectedEntityNames
)
}
if (this.props.isInStandalonePage) this.setCanonicalUrl()
this.grapher?.populateFromQueryParams(url.queryParams)
exposeInstanceOnWindow(this, "explorer")
this.attachEventListeners()
this.updateEntityPickerTable() // call for the first time to initialize EntityPicker
}
componentDidUpdate() {
this.maybeUpdatePageTitle()
}
private maybeUpdatePageTitle() {
// expose the title of the current view to the Google crawler on non-default views
// of opted-in standalone explorer pages
if (
this.props.isInStandalonePage &&
this.grapher &&
this.explorerProgram.indexViewsSeparately &&
document.location.search
) {
document.title = `${this.grapher.displayTitle} - Our World in Data`
}
}
private setCanonicalUrl() {
// see https://developers.google.com/search/docs/advanced/javascript/javascript-seo-basics#properly-inject-canonical-links
// Note that the URL is not updated when the user interacts with the explorer - this should be enough for Googlebot I hope.
const canonicalElement = document.createElement("link")
canonicalElement.setAttribute("rel", "canonical")
canonicalElement.href = this.canonicalUrlForGoogle
document.head.appendChild(canonicalElement)
}
private attachEventListeners() {
if (typeof window !== "undefined" && "ResizeObserver" in window) {
const onResizeThrottled = debounce(this.onResize, 200, {
leading: true,
})
const resizeObserver = new ResizeObserver(onResizeThrottled)
resizeObserver.observe(this.grapherContainerRef.current!)
this.disposers.push(() => {
resizeObserver.disconnect()
})
} else if (
typeof window === "object" &&
typeof document === "object" &&
!navigator.userAgent.includes("jsdom")
) {
// only show the warning when we're in something that roughly resembles a browser
console.warn(
"ResizeObserver not available; the explorer will not be responsive to window resizes"
)
Bugsnag?.notify("ResizeObserver not available")
this.onResize() // fire once to initialize, at least
}
// We always prefer the entity picker metric to be sourced from the currently displayed table.
// To do this properly, we need to also react to the table changing.
this.disposers.push(
reaction(
() => [
this.entityPickerMetric,
this.explorerProgram.grapherConfig.tableSlug,
],
() => this.updateEntityPickerTable()
)
)
if (this.props.isInStandalonePage) this.bindToWindow()
}
componentWillUnmount() {
this.disposers.forEach((dispose) => dispose())
}
private initSlideshow() {
const grapher = this.grapher
if (!grapher || grapher.slideShow) return
grapher.slideShow = new SlideShowController(
this.explorerProgram.decisionMatrix.allDecisionsAsQueryParams(),
0,
this
)
}
private persistedGrapherQueryParamsBySelectedRow: Map<
number,
Partial<GrapherQueryParams>
> = new Map()
// todo: break this method up and unit test more. this is pretty ugly right now.
@action.bound private reactToUserChangingSelection(oldSelectedRow: number) {
if (!this.grapher || !this.explorerProgram.currentlySelectedGrapherRow)
return // todo: can we remove this?
this.initSlideshow()
const oldGrapherParams = this.grapher.changedParams
this.persistedGrapherQueryParamsBySelectedRow.set(
oldSelectedRow,
oldGrapherParams
)
const newGrapherParams = {
...this.persistedGrapherQueryParamsBySelectedRow.get(
this.explorerProgram.currentlySelectedGrapherRow
),
country: oldGrapherParams.country,
region: oldGrapherParams.region,
time: this.grapher.timeParam,
}
const previousTab = this.grapher.tab
this.updateGrapherFromExplorer()
// preserve the previous tab if that's still available in the new view;
// and use the first tab otherwise, ignoring the table
const tabsWithoutTable = this.grapher.availableTabs.filter(
(tab) => tab !== GrapherTabOption.table
)
newGrapherParams.tab = this.grapher.availableTabs.includes(previousTab)
? previousTab
: tabsWithoutTable[0] ?? GrapherTabOption.table
this.grapher.populateFromQueryParams(newGrapherParams)
}
@action.bound private setGrapherTable(table: OwidTable) {
if (this.grapher) {
this.grapher.inputTable = table
this.grapher.appendNewEntitySelectionOptions()
}
}
private futureGrapherTable = new PromiseSwitcher<OwidTable>({
onResolve: (table) => this.setGrapherTable(table),
onReject: (error) => this.grapher?.setError(error),
})
tableLoader = new PromiseCache((slug: TableSlug | undefined) =>
this.explorerProgram.constructTable(slug)
)
@action.bound private updateGrapherFromExplorer() {
switch (this.explorerProgram.chartCreationMode) {
case ExplorerChartCreationMode.FromGrapherId:
this.updateGrapherFromExplorerUsingGrapherId()
break
case ExplorerChartCreationMode.FromVariableIds:
void this.updateGrapherFromExplorerUsingVariableIds()
break
case ExplorerChartCreationMode.FromExplorerTableColumnSlugs:
this.updateGrapherFromExplorerUsingColumnSlugs()
break
}
}
@action.bound private updateGrapherFromExplorerCommon() {
const grapher = this.grapher
if (!grapher) return
const {
yScaleToggle,
yAxisMin,
facetYDomain,
relatedQuestionText,
relatedQuestionUrl,
mapTargetTime,
} = this.explorerProgram.grapherConfig
grapher.yAxis.canChangeScaleType = yScaleToggle
grapher.yAxis.min = yAxisMin
if (facetYDomain) {
grapher.yAxis.facetDomain = facetYDomain
}
if (relatedQuestionText && relatedQuestionUrl) {
grapher.relatedQuestions = [
{ text: relatedQuestionText, url: relatedQuestionUrl },
]
}
if (mapTargetTime) {
grapher.map.time = mapTargetTime
}
grapher.slug = this.explorerProgram.slug
if (!grapher.id) grapher.id = 0
}
@computed private get columnDefsWithoutTableSlugByIdOrSlug(): Record<
number | string,
OwidColumnDef
> {
const { columnDefsWithoutTableSlug } = this.explorerProgram
return keyBy(
columnDefsWithoutTableSlug,
(def: OwidColumnDef) => def.owidVariableId ?? def.slug
)
}
// gets the slugs of all base and intermediate columns that a
// transformed column depends on; for example, if a column's transform
// is 'divideBy 170775 other_slug' and 'other_slug' is also a transformed
// column defined by 'multiplyBy 539022 2', then this function
// returns ['539022', '170775', 'other_slug']
private getBaseColumnsForColumnWithTransform(slug: string): string[] {
const def = this.columnDefsWithoutTableSlugByIdOrSlug[slug]
if (!def?.transform) return []
const dataSlugs =
extractPotentialDataSlugsFromTransform(def.transform) ?? []
return dataSlugs.flatMap((dataSlug) => [
...this.getBaseColumnsForColumnWithTransform(dataSlug),
dataSlug,
])
}
// gets the IDs of all variables that a transformed column depends on;
// for example, if a there are two columns, 'slug' and 'other_slug', that
// are defined by the transforms 'divideBy 170775 other_slug' and 'multiplyBy 539022 2',
// respectively, then getBaseVariableIdsForColumnWithTransform('slug')
// returns ['539022', '170775'] as these are the IDs of the two variables
// that the 'slug' column depends on
private getBaseVariableIdsForColumnWithTransform(slug: string): string[] {
const { columnDefsWithoutTableSlug } = this.explorerProgram
const baseVariableIdsAndColumnSlugs =
this.getBaseColumnsForColumnWithTransform(slug)
const slugsInColumnBlock: string[] = columnDefsWithoutTableSlug
.filter((def) => !def.owidVariableId)
.map((def) => def.slug)
return baseVariableIdsAndColumnSlugs.filter(
(variableIdOrColumnSlug) =>
!slugsInColumnBlock.includes(variableIdOrColumnSlug)
)
}
@action.bound private updateGrapherFromExplorerUsingGrapherId() {
const grapher = this.grapher
if (!grapher) return
const { grapherId } = this.explorerProgram.grapherConfig
const grapherConfig = this.grapherConfigs.get(grapherId!) ?? {}
const config: GrapherProgrammaticInterface = {
...grapherConfig,
...this.explorerProgram.grapherConfigOnlyGrapherProps,
bakedGrapherURL: BAKED_GRAPHER_URL,
dataApiUrl: DATA_API_URL,
hideEntityControls: this.showExplorerControls,
manuallyProvideData: false,
}
// if not empty, respect the explorer's selection
if (this.selection.hasSelection) {
config.selectedEntityNames = this.selection.selectedEntityNames
}
grapher.setAuthoredVersion(config)
grapher.reset()
this.updateGrapherFromExplorerCommon()
grapher.updateFromObject(config)
grapher.downloadData()
}
@action.bound private async updateGrapherFromExplorerUsingVariableIds() {
const grapher = this.grapher
if (!grapher) return
const {
yVariableIds = "",
xVariableId,
colorVariableId,
sizeVariableId,
ySlugs = "",
xSlug,
colorSlug,
sizeSlug,
} = this.explorerProgram.grapherConfig
const yVariableIdsList = yVariableIds
.split(" ")
.map(parseIntOrUndefined)
.filter((item) => item !== undefined)
const partialGrapherConfig =
this.partialGrapherConfigsByVariableId.get(yVariableIdsList[0]) ??
{}
const config: GrapherProgrammaticInterface = {
...partialGrapherConfig,
...this.explorerProgram.grapherConfigOnlyGrapherProps,
bakedGrapherURL: BAKED_GRAPHER_URL,
dataApiUrl: DATA_API_URL,
hideEntityControls: this.showExplorerControls,
manuallyProvideData: false,
}
// if not empty, respect the explorer's selection
if (this.selection.hasSelection) {
config.selectedEntityNames = this.selection.selectedEntityNames
}
// set given variable IDs as dimensions to make Grapher
// download the data and metadata for these variables
const dimensions = config.dimensions?.slice() ?? []
yVariableIdsList.forEach((yVariableId) => {
dimensions.push({
variableId: yVariableId,
property: DimensionProperty.y,
})
})
if (xVariableId) {
const maybeXVariableId = parseIntOrUndefined(xVariableId)
if (maybeXVariableId !== undefined)
dimensions.push({
variableId: maybeXVariableId,
property: DimensionProperty.x,
})
}
if (colorVariableId) {
const maybeColorVariableId = parseIntOrUndefined(colorVariableId)
if (maybeColorVariableId !== undefined)
dimensions.push({
variableId: maybeColorVariableId,
property: DimensionProperty.color,
})
}
if (sizeVariableId) {
const maybeSizeVariableId = parseIntOrUndefined(sizeVariableId)
if (maybeSizeVariableId !== undefined)
dimensions.push({
variableId: maybeSizeVariableId,
property: DimensionProperty.size,
})
}
// Slugs that are used to create a chart refer to columns derived from variables
// by a transform string (e.g. 'multiplyBy 539022 2'). To render such a chart, we
// need to download the data for all variables the transformed columns depend on
// and construct an appropriate Grapher table. This is done in three steps:
// 1. find all variables that the transformed columns depend on and add them to
// the config's dimensions array
// 2. download data and metadata of the variables
// 3. append the transformed columns to the Grapher table (note that this includes
// intermediate columns that are defined for multi-step transforms but are not
// referred to in any Grapher row)
// all slugs specified by the author in the explorer config
const uniqueSlugsInGrapherRow = uniq(
[...ySlugs.split(" "), xSlug, colorSlug, sizeSlug].filter(identity)
) as string[]
// find all variables that the transformed columns depend on and add them to the dimensions array
if (uniqueSlugsInGrapherRow.length) {
const baseVariableIds = uniq(
uniqueSlugsInGrapherRow.flatMap((slug) =>
this.getBaseVariableIdsForColumnWithTransform(slug)
)
)
.map((id) => parseInt(id, 10))
.filter((id) => !isNaN(id))
baseVariableIds.forEach((variableId) => {
const hasDimension = dimensions.some(
(d) => d.variableId === variableId
)
if (!hasDimension) {
dimensions.push({
variableId: variableId,
property: DimensionProperty.table, // no specific dimension
})
}
})
}
config.dimensions = dimensions
if (config.ySlugs && yVariableIds) config.ySlugs += " " + yVariableIds
const inputTableTransformer = (table: OwidTable) => {
// add transformed (and intermediate) columns to the grapher table
if (uniqueSlugsInGrapherRow.length) {
const allColumnSlugs = uniq(
uniqueSlugsInGrapherRow.flatMap((slug) => [
...this.getBaseColumnsForColumnWithTransform(slug),
slug,
])
)
const existingColumnSlugs = table.columnSlugs
const outstandingColumnSlugs = allColumnSlugs.filter(
(slug) => !existingColumnSlugs.includes(slug)
)
const requiredColumnDefs = outstandingColumnSlugs
.map(
(slug) =>
this.columnDefsWithoutTableSlugByIdOrSlug[slug]
)
.filter(identity)
table = table.appendColumns(requiredColumnDefs)
}
// update column definitions with manually provided properties
table = table.updateDefs((def: OwidColumnDef) => {
const manuallyProvidedDef =
this.columnDefsWithoutTableSlugByIdOrSlug[def.slug] ?? {}
const mergedDef = { ...def, ...manuallyProvidedDef }
// update display properties
mergedDef.display = mergedDef.display ?? {}
if (manuallyProvidedDef.name)
mergedDef.display.name = manuallyProvidedDef.name
if (manuallyProvidedDef.unit)
mergedDef.display.unit = manuallyProvidedDef.unit
if (manuallyProvidedDef.shortUnit)
mergedDef.display.shortUnit = manuallyProvidedDef.shortUnit
return mergedDef
})
return table
}
grapher.setAuthoredVersion(config)
grapher.reset()
this.updateGrapherFromExplorerCommon()
grapher.updateFromObject(config)
if (dimensions.length === 0) {
// If dimensions are empty, explicitly set the table to an empty table
// so we don't end up confusingly showing stale data from a previous chart
grapher.receiveOwidData(new Map())
} else {
await grapher.downloadLegacyDataFromOwidVariableIds(
inputTableTransformer
)
}
}
@action.bound private updateGrapherFromExplorerUsingColumnSlugs() {
const grapher = this.grapher
if (!grapher) return
const { tableSlug } = this.explorerProgram.grapherConfig
const config: GrapherProgrammaticInterface = {
...this.explorerProgram.grapherConfigOnlyGrapherProps,
bakedGrapherURL: BAKED_GRAPHER_URL,
dataApiUrl: DATA_API_URL,
hideEntityControls: this.showExplorerControls,
manuallyProvideData: true,
}
// if not empty, respect the explorer's selection
if (this.selection.hasSelection) {
config.selectedEntityNames = this.selection.selectedEntityNames
}
grapher.setAuthoredVersion(config)
grapher.reset()
this.updateGrapherFromExplorerCommon()
grapher.updateFromObject(config)
// Clear any error messages, they are likely to be related to dataset loading.
this.grapher?.clearErrors()
// Set a table immediately. A BlankTable shows a loading animation.
this.setGrapherTable(
BlankOwidTable(tableSlug, `Loading table '${tableSlug}'`)
)
void this.futureGrapherTable.set(this.tableLoader.get(tableSlug))
if (this.downloadDataLink)
grapher.externalCsvLink = this.downloadDataLink
}
@action.bound setSlide(choiceParams: ExplorerFullQueryParams) {
this.explorerProgram.decisionMatrix.setValuesFromChoiceParams(
choiceParams
)
}
@computed private get currentChoiceParams(): ExplorerChoiceParams {
const { decisionMatrix } = this.explorerProgram
return decisionMatrix.currentParams
}
@computed get queryParams(): ExplorerFullQueryParams {
if (!this.grapher) return {}
if (window.location.href.includes(EXPLORERS_PREVIEW_ROUTE))
localStorage.setItem(
UNSAVED_EXPLORER_PREVIEW_QUERYPARAMS +
this.explorerProgram.slug,
JSON.stringify(this.currentChoiceParams)
)
let url = Url.fromQueryParams(
omitUndefinedValues({
...this.grapher.changedParams,
pickerSort: this.entityPickerSort,
pickerMetric: this.entityPickerMetric,
hideControls: this.initialQueryParams.hideControls || undefined,
...this.currentChoiceParams,
})
)
url = setSelectedEntityNamesParam(
url,
this.selection.hasSelection
? this.selection.selectedEntityNames
: undefined
)
return url.queryParams as ExplorerFullQueryParams
}
@computed get currentUrl(): Url {
if (this.props.isPreview) return Url.fromQueryParams(this.queryParams)
return Url.fromURL(this.baseUrl).setQueryParams(this.queryParams)
}
@computed get canonicalUrlForGoogle(): string {
// we want the canonical URL to match what's in the sitemap, so it's different depending on indexViewsSeparately
if (this.explorerProgram.indexViewsSeparately)
return Url.fromURL(this.baseUrl).setQueryParams(
this.currentChoiceParams
).fullUrl
else return this.baseUrl
}
private bindToWindow() {
// There is a surprisingly considerable performance overhead to updating the url
// while animating, so we debounce to allow e.g. smoother timelines
const pushParams = () => setWindowUrl(this.currentUrl)
const debouncedPushParams = debounce(pushParams, 100)
this.disposers.push(
reaction(
() => this.queryParams,
() =>
this.grapher?.debounceMode
? debouncedPushParams()
: pushParams()
)
)
}
private get panels() {
return this.explorerProgram.decisionMatrix.choicesWithAvailability.map(
(choice) => (
<ExplorerControlPanel
key={choice.title}
explorerSlug={this.explorerProgram.slug}
choice={choice}
onChange={this.onChangeChoice(choice.title)}
isMobile={this.isNarrow}
/>
)
)
}
onChangeChoice = (choiceTitle: string) => (value: string) => {
const { currentlySelectedGrapherRow } = this.explorerProgram
this.explorerProgram.decisionMatrix.setValueCommand(choiceTitle, value)
if (currentlySelectedGrapherRow)
this.reactToUserChangingSelection(currentlySelectedGrapherRow)
}
private renderHeaderElement() {
return (
<div className="ExplorerHeaderBox">
<div className="ExplorerTitle">
{this.explorerProgram.explorerTitle} Data Explorer
</div>
<div className="ExplorerSubtitle">
<MarkdownTextWrap
fontSize={12}
text={this.explorerProgram.explorerSubtitle || ""}
/>
</div>
{this.explorerProgram.downloadDataLink && (
<a
href={this.explorerProgram.downloadDataLink}
target="_blank"
rel="noopener noreferrer"
className="ExplorerDownloadLink"
>
Download this dataset
</a>
)}
</div>
)
}
@observable private isNarrow = isNarrow()
@computed private get isInIFrame() {
return isInIFrame()
}
@computed private get showExplorerControls() {
if (!this.props.isEmbeddedInAnOwidPage && !this.isInIFrame) return true
// Only allow hiding controls on embedded pages
return !(
this.explorerProgram.hideControls ||
this.initialQueryParams.hideControls === "true"
)
}
@computed private get downloadDataLink(): string | undefined {
return this.explorerProgram.downloadDataLink
}
@observable
private grapherContainerRef: React.RefObject<HTMLDivElement> =
React.createRef()
@observable.ref private grapherBounds = DEFAULT_BOUNDS
@observable.ref
private grapherRef: React.RefObject<Grapher> = React.createRef()
private renderControlBar() {
return (
<ExplorerControlBar
isMobile={this.isNarrow}
showControls={this.showMobileControlsPopup}
closeControls={this.closeControls}
>
{this.panels}
</ExplorerControlBar>
)
}
private renderEntityPicker() {
return (
<EntityPicker
key="entityPicker"
manager={this}
isDropdownMenu={this.isNarrow}
/>
)
}
@action.bound private toggleMobileControls() {
this.showMobileControlsPopup = !this.showMobileControlsPopup
}
@action.bound private onResize() {
// Don't bother rendering if the container is hidden
// see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
if (this.grapherContainerRef.current?.offsetParent === null) return
const oldIsNarrow = this.isNarrow
this.isNarrow = isNarrow()
this.updateGrapherBounds()
// If we changed between narrow and wide mode, we need to wait for CSS changes to kick in
// to properly calculate the new grapher bounds
if (this.isNarrow !== oldIsNarrow)
window.setTimeout(() => this.updateGrapherBounds(), 0)
}
// Todo: add better logic to maximize the size of the Grapher
private updateGrapherBounds() {
const grapherContainer = this.grapherContainerRef.current
if (grapherContainer)
this.grapherBounds = new Bounds(
0,
0,
grapherContainer.clientWidth,
grapherContainer.clientHeight
)
}
@observable private showMobileControlsPopup = false
private get mobileCustomizeButton() {
return (
<a
className="btn btn-primary mobile-button"
onClick={this.toggleMobileControls}
data-track-note="explorer_customize_chart_mobile"
>
<FontAwesomeIcon icon={faChartLine} /> Customize chart
</a>
)
}
@action.bound private closeControls() {
this.showMobileControlsPopup = false
}
// todo: add tests for this and better tests for this class in general
@computed private get showHeaderElement() {
return (
this.showExplorerControls &&
this.explorerProgram.explorerTitle &&
this.panels.length > 0
)
}
render() {
const { showExplorerControls, showHeaderElement } = this
return (
<div
className={classNames({
Explorer: true,
"mobile-explorer": this.isNarrow,
HideControls: !showExplorerControls,
"is-embed": this.props.isEmbeddedInAnOwidPage,
})}
>
{showHeaderElement && this.renderHeaderElement()}
{showHeaderElement && this.renderControlBar()}
{showExplorerControls && this.renderEntityPicker()}
{showExplorerControls &&
this.isNarrow &&
this.mobileCustomizeButton}
<div className="ExplorerFigure" ref={this.grapherContainerRef}>