forked from owid/owid-grapher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrapherConfigGridEditor.tsx
1801 lines (1679 loc) · 71.1 KB
/
GrapherConfigGridEditor.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 {
Bounds,
stringifyUnknownError,
excludeUndefined,
moveArrayItemToIndex,
getWindowUrl,
setWindowUrl,
excludeNull,
mergeGrapherConfigs,
} from "@ourworldindata/utils"
import { GrapherConfigPatch } from "../adminShared/AdminSessionTypes.js"
import {
applyPatch,
setValueRecursiveInplace,
} from "../adminShared/patchHelper.js"
import {
FieldDescription,
extractFieldDescriptionsFromSchema,
FieldType,
EditorOption,
} from "../adminShared/schemaProcessing.js"
import {
DragDropContext,
Droppable,
Draggable,
DropResult,
} from "react-beautiful-dnd"
import { Disposer, observer } from "mobx-react"
import { observable, computed, action, runInAction, autorun } from "mobx"
import { match, P } from "ts-pattern"
import {
cloneDeep,
isArray,
isEmpty,
isEqual,
isNil,
omitBy,
pick,
range,
} from "lodash"
import { BaseEditorComponent, HotColumn, HotTable } from "@handsontable/react"
import { AdminAppContext, AdminAppContextType } from "./AdminAppContext.js"
import Handsontable from "handsontable"
import { ChartTypeName } from "@ourworldindata/types"
import {
Grapher,
GrapherProgrammaticInterface,
MapChart,
} from "@ourworldindata/grapher"
import { BindString, SelectField, Toggle } from "./Forms.js"
import { from } from "rxjs"
import {
catchError,
debounceTime,
distinctUntilChanged,
switchMap,
} from "rxjs/operators"
import { fromFetch } from "rxjs/fetch"
import { toStream, fromStream } from "mobx-utils"
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons"
import {
parseVariableAnnotationsRow,
VariableAnnotationsRow,
ColumnInformation,
Action,
PAGEING_SIZE,
Tabs,
ALL_TABS,
ColumnSet,
FetchVariablesParameters,
fetchVariablesParametersToQueryParametersString,
IconToggleComponent,
getItemStyle,
isConfigColumn,
filterTreeToSExpression,
FilterPanelState,
filterPanelInitialConfig,
initialFilterQueryValue,
fieldDescriptionToFilterPanelFieldConfig,
simpleColumnToFilterPanelFieldConfig,
renderBuilder,
GrapherConfigGridEditorProps,
GrapherConfigGridEditorConfig,
ColumnDataSource,
ColumnDataSourceType,
ColumnDataSourceUnknown,
SExpressionToJsonLogic,
fetchVariablesParametersFromQueryString,
filterExpressionNoFilter,
fetchVariablesParametersToQueryParameters,
postprocessJsonLogicTree,
} from "./GrapherConfigGridEditorTypesAndUtils.js"
import {
Query,
Utils as QbUtils,
Utils,
SimpleField,
Config,
ImmutableTree,
} from "@react-awesome-query-builder/antd"
import codemirror from "codemirror"
import { UnControlled as CodeMirror } from "react-codemirror2"
import jsonpointer from "json8-pointer"
import { EditorColorScaleSection } from "./EditorColorScaleSection.js"
import { Operation } from "../adminShared/SqlFilterSExpression.js"
function HotColorScaleRenderer() {
return <div style={{ color: "gray" }}>Color scale</div>
}
/**
* This cell editor component explicitly does nothing. It is used for color scale columns
* where we don't want to make the cells read only so that copy/paste etc still work but
* at the same time we don't want the user to be able to edit the cells directly (instead
* they should use the sidebar editor)
*/
class HotColorScaleEditor extends BaseEditorComponent<any> {
constructor(props: Record<string, never>) {
super(props)
}
getValue() {
return undefined
}
prepare(
row: any,
col: any,
prop: any,
td: any,
originalValue: any,
cellProperties: any
) {
// We'll need to call the `prepare` method from
// the `BaseEditorComponent` class, as it provides
// the component with the information needed to use the editor
// (hotInstance, row, col, prop, TD, originalValue, cellProperties)
super.prepare(row, col, prop, td, originalValue, cellProperties)
// const tdPosition = td.getBoundingClientRect();
// As the `prepare` method is triggered after selecting
// any cell, we're updating the styles for the editor element,
// so it shows up in the correct position.
}
render() {
return <div id="colorScaleEditorElement"></div>
}
}
@observer
export class GrapherConfigGridEditor extends React.Component<GrapherConfigGridEditorProps> {
static contextType = AdminAppContext
@observable.ref grapher = new Grapher() // the grapher instance we keep around and update
@observable.ref grapherElement?: React.ReactElement // the JSX Element of the preview IF we want to display it currently
numTotalRows: number | undefined = undefined
@observable selectedRow: number | undefined = undefined
@observable selectionEndRow: number | undefined = undefined
@observable selectedColumn: number | undefined = undefined
@observable selectionEndColumn: number | undefined = undefined
@observable activeTab = Tabs.FilterTab
@observable currentColumnSet: ColumnSet
@observable columnFilter: string = ""
@observable hasUncommitedRichEditorChanges: boolean = false
@observable.ref columnSelection: ColumnInformation[] = []
@observable.ref filterState: FilterPanelState | undefined = undefined
context!: AdminAppContextType
/** This array contains a description for every column, information like which field
to display, what editor control should be used, ... */
@observable.ref fieldDescriptions: FieldDescription[] | undefined =
undefined
/** Rows of the query result to the /variable-annotations endpoint that include a parsed
grapher object for the grapherConfig field */
@observable richDataRows: VariableAnnotationsRow[] | undefined = undefined
/** Undo stack - not yet used - TODO: implement Undo/redo */
@observable undoStack: Action[] = []
/** Redo stack - not yet used */
@observable redoStack: Action[] = []
@observable keepEntitySelectionOnChartChange: boolean = false
/** This field stores the offset of what is currently displayed on screen */
@observable currentPagingOffset: number = 0
/** This field stores the offset that the user requested. E.g. if the user clicks
the "Next page" quickly twice then this field will be 2 paging offsets higher
than currentPagingOffset until the request to retrieve that data is complete
at which point they will be the same */
@observable desiredPagingOffset: number = 0
// Sorting fields - not yet used - TODO: implement sorting
@observable sortByColumn: string = "id"
@observable sortByAscending: boolean = false
readonly config: GrapherConfigGridEditorConfig
disposers: Disposer[] = []
constructor(props: GrapherConfigGridEditorProps) {
super(props)
this.config = props.config
this.currentColumnSet = this.config.columnSet[0]
}
/** Computed property that combines all relevant filter, paging and offset
properties into a FetchVariablesParameter object that is used to construct
the query */
@computed get dataFetchParameters(): FetchVariablesParameters {
const {
desiredPagingOffset,
sortByAscending,
sortByColumn,
filterSExpression,
numTotalRows,
} = this
const filterQuery = filterSExpression ?? filterExpressionNoFilter
const offsetToUse = numTotalRows
? Math.max(
0,
Math.min(desiredPagingOffset / 50, numTotalRows / 50 - 1)
) * 50
: desiredPagingOffset
return {
offset: offsetToUse,
filterQuery,
sortByColumn,
sortByAscending,
}
}
/** Here is some of the most important code in this component - the
setup that puts in place the fetch logic to retrieve variable annotations
whenever any of the dataFetchParameters change */
async componentDidMount() {
const url = getWindowUrl()
const queryParamsAsDataFetchParams =
fetchVariablesParametersFromQueryString(
url.queryParams,
this.config.sExpressionContext
)
const nonDefaultDataFetchQueryParams = !isEqual(
this.dataFetchParameters,
queryParamsAsDataFetchParams
)
// Here we chain together a mobx property (dataFetchParameters) to
// an rxJS observable pipeline to debounce the signal and then
// use switchMap to create new fetch requests and cancel outstanding ones
// to finally turn this into a local mobx value again that we subscribe to
// with an autorun to finally update the dependent properties on this class.
const varStream = toStream(
() => this.dataFetchParameters,
!nonDefaultDataFetchQueryParams
)
const observable = from(varStream).pipe(
debounceTime(200), // debounce by 200 MS (this also introduces a min delay of 200ms)
distinctUntilChanged(isEqual), // don't emit new values if the value hasn't changed
switchMap((params) => {
// use switchmap to create a new fetch (as an observable) and
// automatically cancel stale fetch requests
return fromFetch(this.buildDataFetchUrl(params), {
headers: { Accept: "application/json" },
credentials: "same-origin",
selector: (response) => response.json(),
}).pipe(
// catch errors and report them the way the admin UI expects it
catchError((err: any /*, caught: Observable<any> */) => {
this.context.admin.setErrorMessage({
title: `Failed to fetch indicator annotations`,
content:
stringifyUnknownError(err) ??
"unexpected error value in setErrorMessage",
isFatal: false,
})
return [undefined]
})
)
})
)
// Turn the rxJs observable stream into a mobx value
const mobxValue = fromStream(observable)
// Set up the autorun to run an action to update the dependendencies
const disposer = autorun(() => {
const currentData = mobxValue.current
if (currentData !== undefined) {
runInAction(() => {
this.resetViewStateAfterFetch()
this.currentPagingOffset = this.desiredPagingOffset
this.richDataRows = currentData.rows.map(
parseVariableAnnotationsRow
)
this.numTotalRows = currentData.numTotalRows
})
}
})
// Add the disposer to the list of things we need to clean up on unmount
this.disposers.push(disposer)
void this.getFieldDefinitions()
}
@action.bound private resetViewStateAfterFetch(): void {
this.undoStack = []
this.redoStack = []
this.selectedRow = undefined
this.grapherElement = undefined
}
@action.bound private loadGrapherJson(json: any): void {
const newConfig: GrapherProgrammaticInterface = {
...json,
isEmbeddedInAnOwidPage: true,
bounds: new Bounds(0, 0, 480, 500),
getGrapherInstance: (grapher: Grapher) => {
this.grapher = grapher
},
dataApiUrlForAdmin:
this.context.admin.settings.DATA_API_FOR_ADMIN_UI, // passed this way because clientSettings are baked and need a recompile to be updated
}
if (this.grapherElement) {
this.grapher.setAuthoredVersion(newConfig)
this.grapher.reset()
if (!this.keepEntitySelectionOnChartChange)
// this resets the entity selection to what the author set in the chart config
// This is user controlled because when working with existing charts this is usually desired
// but when working on the variable level where this is missing it is often nicer to keep
// the same country selection as you zap through the variables
this.grapher.clearSelection()
this.grapher.updateFromObject(newConfig)
this.grapher.downloadData()
} else this.grapherElement = <Grapher {...newConfig} />
}
@action private updatePreviewToRow(): void {
const { selectedRowContent } = this
if (selectedRowContent === undefined) return
// Get the grapherConfig of the currently selected row and then
// merge it with the necessary partial information (e.g. variableId field)
// to get a config that actually works in all cases
const grapherConfig = selectedRowContent.config
const finalConfigLayer = this.config.finalVariableLayerModificationFn(
selectedRowContent.id
)
const mergedConfig = mergeGrapherConfigs(
grapherConfig,
finalConfigLayer
)
this.loadGrapherJson(mergedConfig)
}
@computed private get columnDataSource(): ColumnDataSource | undefined {
const { selectedRowContent, columnDataSources, selectedColumn } = this
if (selectedRowContent === undefined) return undefined
if (
selectedColumn === undefined ||
selectedColumn >= columnDataSources.length
) {
return undefined
}
return columnDataSources[selectedColumn]
}
@computed private get currentColumnFieldDescription():
| FieldDescription
| undefined {
const { columnDataSource } = this
return match(columnDataSource)
.with(
{ kind: ColumnDataSourceType.FieldDescription },
(source) => source.description
)
.otherwise(() => undefined)
}
@action.bound
private onRichTextEditorChange(
editor: codemirror.Editor,
data: codemirror.EditorChange,
value: string
) {
if (data.origin !== undefined) {
// origin seems to be +input when editing and undefined when we change the value programmatically
const { currentColumnFieldDescription, grapher } = this
if (currentColumnFieldDescription === undefined) return
this.hasUncommitedRichEditorChanges = true
const pointer = jsonpointer.parse(
currentColumnFieldDescription.pointer
) as string[]
// Here we are setting the target column field directly at the grapher so the
// preview is updated. When the user clicks the save button we'll then check
// the value on grapher vs the value on the richDataRow and perform a proper
// update using doAction like we do on the grid editor commits.
setValueRecursiveInplace(grapher, pointer, value)
}
}
@action.bound
commitRichEditorChanges() {
this.commitOrCancelRichEditorChanges(true)
}
@action.bound
cancelRichEditorChanges() {
this.commitOrCancelRichEditorChanges(false)
}
@action.bound
commitOrCancelRichEditorChanges(performCommit: boolean) {
const { selectedRowContent, currentColumnFieldDescription, grapher } =
this
if (
selectedRowContent === undefined ||
currentColumnFieldDescription === undefined
)
return
const pointer = jsonpointer.parse(
currentColumnFieldDescription.pointer
) as string[]
const prevVal = currentColumnFieldDescription.getter(
selectedRowContent.config as Record<string, unknown>
)
if (performCommit) {
const grapherObject = { ...this.grapher.object }
const newVal = currentColumnFieldDescription.getter(
grapherObject as Record<string, unknown>
)
const patch: GrapherConfigPatch = {
id: selectedRowContent.id,
oldValue: prevVal,
newValue: newVal,
jsonPointer: currentColumnFieldDescription.pointer,
oldValueIsEquivalentToNullOrUndefined:
currentColumnFieldDescription.default !== undefined &&
currentColumnFieldDescription.default === prevVal,
}
void this.doAction({ patches: [patch] })
} else {
setValueRecursiveInplace(grapher, pointer, prevVal)
}
this.hasUncommitedRichEditorChanges = false
}
@action.bound
onGenericRichEditorChange() {
this.hasUncommitedRichEditorChanges = true
}
@computed get editControl(): React.ReactElement | undefined {
const { currentColumnFieldDescription, grapher, selectedRowContent } =
this
if (
currentColumnFieldDescription === undefined ||
selectedRowContent === undefined
)
return undefined
return match(currentColumnFieldDescription.editor)
.with(
EditorOption.primitiveListEditor,
() =>
// TODO: handle different kinds of arrays here. In effect, the ones to handle are
// includedEntities, excludedEntities (both with a yet to extract control)
// selection. The seleciton should be refactored because ATM it's 3 arrays and it
// is annoying to keep those in sync and target more than one field with a column.
undefined
)
.with(EditorOption.colorEditor, () => {
if (currentColumnFieldDescription?.pointer.startsWith("/map")) {
// TODO: remove this hack once map is more similar to other charts
const mapChart = new MapChart({ manager: this.grapher })
const colorScale = mapChart.colorScale
// TODO: instead of using onChange below that has to be maintained when
// the color scale changes I tried to use a reaction here after Daniel G's suggestion
// but I couldn't get this to work. Worth trying again later.
// this.editControlDisposerFn = reaction(
// () => colorScale,
// () => this.onGenericRichEditorChange(),
// { equals: comparer.structural }
// )
return colorScale ? (
<EditorColorScaleSection
scale={colorScale}
chartType={ChartTypeName.WorldMap}
features={{
visualScaling: true,
legendDescription: false,
}}
showLineChartColors={false}
onChange={this.onGenericRichEditorChange}
/>
) : undefined
} else {
if (grapher.chartInstanceExceptMap.colorScale) {
const colorScale =
grapher.chartInstanceExceptMap.colorScale
// TODO: instead of using onChange below that has to be maintained when
// the color scale changes I tried to use a reaction here after Daniel G's suggestion
// but I couldn't get this to work. Worth trying again later.
// this.editControlDisposerFn = reaction(
// () => colorScale,
// () => this.onGenericRichEditorChange(),
// { equals: comparer.structural }
// )
return (
<EditorColorScaleSection
scale={colorScale}
chartType={grapher.type}
features={{
visualScaling: true,
legendDescription: false,
}}
showLineChartColors={grapher.isLineChart}
onChange={this.onGenericRichEditorChange}
/>
)
} else return undefined
}
})
.with(EditorOption.textfield, EditorOption.textarea, () => (
<CodeMirror
value={currentColumnFieldDescription.getter(
grapher as any as Record<string, unknown>
)}
options={{
//theme: "material",
lineNumbers: true,
lineWrapping: true,
}}
autoCursor={false}
onChange={this.onRichTextEditorChange}
/>
))
.otherwise(() => undefined)
}
async sendPatches(patches: GrapherConfigPatch[]): Promise<void> {
await this.context.admin.rawRequest(
this.config.apiEndpoint,
JSON.stringify(patches),
"PATCH"
)
}
/** Used to send the inverse of a patch to undo a change that has previously been performed
*/
async sendReversedPatches(patches: GrapherConfigPatch[]): Promise<void> {
const reversedPatches = patches.map((patch) => ({
...patch,
newValue: patch.oldValue,
oldValue: patch.newValue,
}))
await this.sendPatches(reversedPatches)
}
/** Performs an action - i.e. applies it to the richDataRows object,
sends an HTTP patch request and puts the step onto the undo stack */
@action
async doAction(action: Action): Promise<void> {
const { richDataRows } = this
if (richDataRows === undefined) return
this.undoStack.push(action)
for (const patch of action.patches) {
const rowId = richDataRows.findIndex((row) => row.id === patch.id)
if (rowId === -1)
console.error("Could not find row id in do step!", rowId)
else {
// apply the change to the richDataRows json structure
richDataRows[rowId].config = applyPatch(
patch,
richDataRows[rowId].config
)
}
}
if (this.selectedRow) this.updatePreviewToRow()
await this.sendPatches(action.patches)
}
@action
async undoAction(): Promise<void> {
const { undoStack, redoStack } = this
if (undoStack.length === 0) return
// TODO: not yet properly implemented - figure out how to update the flat data rows and
// set them here. Also change the rich data row entries
const lastStep = undoStack.pop()
redoStack.push(lastStep!)
await this.sendReversedPatches(lastStep!.patches)
}
@action
async redoAction(): Promise<void> {
const { redoStack } = this
if (redoStack.length === 0) return
// TODO: not yet properly implemented - figure out how to update the flat data rows and
// set them here. Also change the rich data row entries
const lastStep = redoStack.pop()
this.undoStack.push(lastStep!)
await this.sendPatches(lastStep!.patches)
}
@computed get fieldDescriptionsMap(): Map<string, FieldDescription> {
const { fieldDescriptions } = this
const map = new Map<string, FieldDescription>()
if (fieldDescriptions === undefined) return map
for (const fieldDescription of fieldDescriptions)
map.set(fieldDescription.pointer, fieldDescription)
return map
}
@computed get defaultValues(): Record<string, any> {
const { fieldDescriptions } = this
if (fieldDescriptions === undefined) return {}
else {
const fields = fieldDescriptions
.filter((field) => field.default !== undefined)
.map((field) => [field.pointer, field.default!] as const)
const asObject = Object.fromEntries(fields)
return asObject
}
}
/** This is an array of data values that is derived from the richDataRows
property. It represents roughly the same logical structure but flattened out
into an array of records where each key is the id of a column (= the json pointer
to the place in the grapherConfig this column represents).
What this function also does is set the default values where we have them in the schema
(which is basically for boolean values and enums) so that the correct defaults are shown.
For example, an entry in this array would have some fields like this:
{
id: ...,
name: ...,
datasetname: ...,
namespacename: ...,
/title: ...,
/subtitle: ...,
/map/projection: ...,
...
} */
@computed get flattenedDataRows(): unknown[] | undefined {
const { richDataRows, fieldDescriptions, defaultValues } = this
if (richDataRows === undefined || fieldDescriptions === undefined)
return undefined
const readOnlyColumns = this.config.readonlyColumns
return this.richDataRows?.map((row) => {
// for every field description try to get the value at this fields json pointer location
// we cloneDeep it so that the value is independent in any case, even array or (in the future) objects
// so that the grid will not change these values directly
const fieldsArray = fieldDescriptions
.map(
(fieldDesc) =>
[
fieldDesc.pointer,
row.config !== undefined
? cloneDeep(
fieldDesc.getter(
row.config as Record<string, unknown>
)
)
: undefined,
] as const
)
.filter(([, val]) => !isNil(val))
const fields = Object.fromEntries(fieldsArray)
const readOnlyColumnValues = [...readOnlyColumns.values()].map(
(field) => [field.key, (row as any)[field.key]]
)
const readOnlyValuesObject =
Object.fromEntries(readOnlyColumnValues)
return {
...readOnlyValuesObject,
...defaultValues,
...fields,
}
})
}
static decideHotType(desc: FieldDescription): string {
// Map the field description editor choice to a handsontable editor.
// We currently map several special types to text when we don't have anything
// fancy implemented
return match(desc.editor)
.with(EditorOption.checkbox, () => "checkbox")
.with(EditorOption.dropdown, () => "dropdown")
.with(EditorOption.numeric, () => "numeric")
.with(EditorOption.numericWithLatestEarliest, () => "numeric")
.with(EditorOption.textfield, () => "text")
.with(EditorOption.textarea, () => "text")
.with(EditorOption.colorEditor, () => "colorScale")
.with(EditorOption.mappingEditor, () => "text")
.with(EditorOption.primitiveListEditor, () => "text")
.exhaustive()
}
static fieldDescriptionToColumn(
desc: FieldDescription
): React.ReactElement {
const name = desc.pointer //.substring(1)
const type = GrapherConfigGridEditor.decideHotType(desc)
if (desc.editor === EditorOption.colorEditor) {
return (
<HotColumn
key={desc.pointer}
settings={{
title: name,
data: desc.pointer,
}}
>
<HotColorScaleRenderer hot-renderer />
<HotColorScaleEditor hot-editor />
</HotColumn>
)
} else
return (
<HotColumn
key={desc.pointer}
settings={{
title: name,
readOnly:
desc.editor === EditorOption.primitiveListEditor ||
desc.editor === EditorOption.mappingEditor,
type: type,
source: desc.enumOptions,
data: desc.pointer,
}}
/>
)
}
@computed get columnDataSources(): ColumnDataSource[] {
const { fieldDescriptions, columnSelection } = this
if (fieldDescriptions === undefined || columnSelection.length === 0)
return []
const readOnlyColumns = this.config.readonlyColumns
const fieldDescriptionsMap = new Map(
fieldDescriptions.map((fieldDesc) => [fieldDesc.pointer, fieldDesc])
)
const columns: ColumnDataSource[] = columnSelection.map(
(columnInformation) => {
if (isConfigColumn(columnInformation.key)) {
const fieldDesc = fieldDescriptionsMap.get(
columnInformation.key
)
if (fieldDesc === undefined) {
return {
kind: ColumnDataSourceType.Unkown,
fieldKey: columnInformation.key,
columnInformation,
}
} else
return {
kind: ColumnDataSourceType.FieldDescription,
description: fieldDesc,
columnInformation,
}
} else {
const readonlyField = readOnlyColumns.get(
columnInformation.key
)
if (readonlyField === undefined) {
return {
kind: ColumnDataSourceType.Unkown,
fieldKey: columnInformation.key,
columnInformation,
}
} else
return {
kind: ColumnDataSourceType.ReadOnlyColumn,
readOnlyColumn: readonlyField,
columnInformation,
}
}
}
)
return columns
}
@computed get hotColumns(): React.ReactElement[] {
const { columnDataSources } = this
const columns = columnDataSources.map((columnDataSource) =>
match(columnDataSource)
.with(
{ kind: ColumnDataSourceType.FieldDescription },
(columnDataSource) =>
GrapherConfigGridEditor.fieldDescriptionToColumn(
columnDataSource.description
)
)
.with(
{ kind: ColumnDataSourceType.ReadOnlyColumn },
(columnDataSource) => (
<HotColumn
key={columnDataSource.readOnlyColumn.key}
settings={{
title: columnDataSource.readOnlyColumn.label,
readOnly: true,
data: columnDataSource.readOnlyColumn.key,
}}
/>
)
)
.with({ kind: ColumnDataSourceType.Unkown }, () => undefined)
.exhaustive()
)
const definedColumns = excludeUndefined(columns)
// If we have columns that we couldn't match, find out which ones they were and console.error them
const undefinedColumns = columnDataSources.filter(
(item): item is ColumnDataSourceUnknown =>
item.kind === ColumnDataSourceType.Unkown
)
if (!isEmpty(undefinedColumns))
console.error("Some columns could not be found!", undefinedColumns)
return definedColumns
}
@action.bound
updateSelection(
row1: number,
column1: number,
row2: number,
column2: number
): void {
if (this.hasUncommitedRichEditorChanges) this.cancelRichEditorChanges()
if (row1 !== this.selectedRow) {
this.hasUncommitedRichEditorChanges = false
this.selectedRow = row1
this.updatePreviewToRow()
}
this.selectionEndRow = row2
if (column1 !== this.selectedColumn) {
this.hasUncommitedRichEditorChanges = false
this.selectedColumn = column1
}
this.selectionEndColumn = column2
}
@computed
private get hotSettings() {
const { flattenedDataRows, columnSelection } = this
const hiddenColumnIndices = columnSelection.flatMap(
(reorderItem, index) => (reorderItem.visible ? [] : [index])
)
if (flattenedDataRows === undefined) return undefined
const hotSettings: Handsontable.GridSettings = {
afterChange: (changes, source) =>
this.processChangedCells(changes, source),
beforeChange: (changes, source) =>
this.validateCellChanges(excludeNull(changes), source),
afterSelectionEnd: (row, column, row2, column2 /*, layer*/) => {
this.updateSelection(row, column, row2, column2)
},
beforeKeyDown: (
event // TODO: check if this works ok with normal editing delete key use
) => (event.key === "Delete" ? this.clearCellContent() : undefined),
modifyColWidth: (width) => {
if (width > 350) {
return 300
}
return undefined
},
allowInsertColumn: false,
allowInsertRow: false,
autoRowSize: false,
autoColumnSize: true,
// cells,
colHeaders: true,
comments: false,
contextMenu: true,
data: flattenedDataRows as Handsontable.RowObject[],
height: "100%",
hiddenColumns: {
columns: hiddenColumnIndices,
copyPasteEnabled: false,
} as any,
manualColumnResize: true,
manualColumnFreeze: true,
manualRowMove: false,
minCols: 1,
minSpareCols: 0,
minRows: 1,
minSpareRows: 0,
rowHeaders: true,
search: false,
stretchH: "all",
width: "100%",
wordWrap: false,
}
return hotSettings
}
@action.bound
clearCellContent() {
const {
selectedRow,
selectedColumn,
selectionEndColumn,
selectionEndRow,
columnDataSources,
richDataRows,
} = this
if (
selectedRow === undefined ||
selectedColumn === undefined ||
selectionEndRow === undefined ||
selectionEndColumn === undefined ||
richDataRows === undefined
)
return
const selectedRows = range(selectedRow, selectionEndRow + 1)
const selectedColumns = range(selectedColumn, selectionEndColumn + 1)
const patches: GrapherConfigPatch[] = []
for (const column of selectedColumns) {
const columnDataSource = columnDataSources[column]
if (
columnDataSource.kind === ColumnDataSourceType.FieldDescription
) {
const pointer = columnDataSource.description.pointer
for (const row of selectedRows) {
const rowData = richDataRows[row]
const prevVal = columnDataSource.description.getter(
rowData.config as Record<string, unknown>
)
const patch: GrapherConfigPatch = {
id: rowData.id,
oldValue: prevVal,
newValue: null,
jsonPointer: pointer,
oldValueIsEquivalentToNullOrUndefined:
columnDataSource.description.default !==
undefined &&
columnDataSource.description.default === prevVal,
}
patches.push(patch)
}
}
}
void this.doAction({ patches })
}
validateCellChanges(
changes: Handsontable.CellChange[] | null,
source: Handsontable.ChangeSource
): boolean | void {
const { fieldDescriptionsMap } = this
// The Handsontable.CellChange is an array of 4 elements: [row, column, oldValue, newValue]. Below
// we have the indices, only a few of them which are used now
const columnIndex = 1
const newValueIndex = 3
// Changes due to loading are always ok (return flags all as ok)
if (source === "loadData" || changes === null) return
// cancel editing if multiple columns are changed at the same time - we
// currently only support changes to a single column at a time
const differentColumns = new Set(
changes.map((change) => change[columnIndex])
)
if (differentColumns.size > 1) return false
const targetColumn = [...differentColumns][0] as string
const columnDefinition = fieldDescriptionsMap.get(targetColumn)
if (columnDefinition === undefined) {
console.error(
"Could not find column definition when trying to verify"
)
return
}
// Since we are editing only values in one column, we strongly assume
// that all values are of the same type (actually supposed to be the same value)
// -> verify this
const allChangesSameType = changes.every(
(change) =>
typeof change[newValueIndex] ===
typeof changes[0][newValueIndex]
)
if (!allChangesSameType) {
console.error("Not all changes were of the same type?")
return
}
// Check if the type matches the target (e.g. to avoid a string value ending
// up in a text field). This is hard to nail down fully but we try to avoid
// such mistakes where possible.
const firstNewValue = changes[0][newValueIndex]
const invalidTypeAssignment = match<
[FieldType | FieldType[], string],