forked from owid/owid-grapher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GrapherConfigGridEditorTypesAndUtils.tsx
570 lines (515 loc) · 18.4 KB
/
GrapherConfigGridEditorTypesAndUtils.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
import {
BinaryLogicOperation,
BinaryLogicOperators,
BooleanAtom,
BooleanOperation,
checkIsPlainObjectWithGuard,
ComparisonOperator,
EditorOption,
EqualityComparision,
EqualityOperator,
excludeUndefined,
FieldDescription,
GrapherConfigPatch,
isArray,
JsonPointerSymbol,
JSONPreciselyTyped,
Negation,
NullCheckOperation,
NullCheckOperator,
NumberAtom,
NumericComparison,
Operation,
OperationContext,
parseToOperation,
QueryParams,
queryParamsToStr,
SqlColumnName,
StringAtom,
StringContainsOperation,
StringOperation,
VariableAnnotationsResponseRow,
} from "@ourworldindata/utils"
import React from "react"
import { IconDefinition } from "@fortawesome/fontawesome-common-types"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome/index.js"
import { GrapherInterface } from "@ourworldindata/types"
import {
AntdConfig,
BasicConfig,
Builder,
BuilderProps,
JsonTree,
SimpleField,
Utils as QbUtils,
JsonGroup,
JsonItem,
Config,
ImmutableTree,
} from "@react-awesome-query-builder/antd"
import { match } from "ts-pattern"
import { isNil } from "lodash"
export function parseVariableAnnotationsRow(
row: VariableAnnotationsResponseRow
): VariableAnnotationsRow {
return row as VariableAnnotationsRow // The type defintiion of VariableAnnotationsResponseRow in clientUtils can't use GrapherInterface so we type cast here for now
}
export enum GrapherConfigGridEditorSource {
SourceVariableAnnotation = "SourceVariableAnnotation",
SourceCharts = "SourceCharts",
}
export interface BulkGrapherConfigRow {
id: number
config: GrapherInterface
createdAt: string
updatedAt: string
}
export interface VariableAnnotationsRow extends BulkGrapherConfigRow {
name: string
datasetname: string
namespacename: string
description: string
}
export interface BulkChartEditRow extends BulkGrapherConfigRow {
lastEditedAt: string
publishedAt: string
lastEditedByUser: string
publishedByUser: string
}
export interface ColumnInformation {
key: string
visible: boolean
description: string
}
export interface Action {
patches: GrapherConfigPatch[]
}
export const PAGEING_SIZE: number = 50
export enum Tabs {
EditorTab = "EditorTab",
FilterTab = "FilterTab",
ColumnsTab = "ColumnsTab",
}
export const ALL_TABS = Object.values(Tabs)
export interface FullColumnSet {
label: "All columns"
kind: "allColumns"
}
export interface SpecificColumnSet {
label: string
kind: "specificColumns"
columns: string[]
}
export type ColumnSet = FullColumnSet | SpecificColumnSet
/** All the parameters we need for making a fully specified request to the /variable-annotations
endpoint. When any of these fields change we need to trigger a new request */
export interface FetchVariablesParameters {
offset: number
filterQuery: Operation
sortByColumn: string // sort is currently ignored but here for future use
sortByAscending: boolean // sort is currently ignored but here for future use
}
export const filterExpressionNoFilter = new BooleanAtom(true)
export function fetchVariablesParametersFromQueryString(
params: QueryParams,
sExpressionContext: OperationContext
): FetchVariablesParameters {
let filterQuery: Operation | undefined = undefined
if (params.hasOwnProperty("filter")) {
filterQuery = parseToOperation(params.filter!, sExpressionContext)
}
return {
offset: Number.parseInt(params.offset ?? "0"),
filterQuery: filterQuery ?? filterExpressionNoFilter,
sortByColumn: params.sortByColumn ?? "id",
sortByAscending: params.sortByAscending === "true",
}
}
export function fetchVariablesParametersToQueryParameters(
params: FetchVariablesParameters
) {
return {
filter: params.filterQuery.toSExpr(),
offset: params.offset.toString(),
sortByColumn: params.sortByColumn,
sortByAscending: params.sortByAscending.toString(),
}
}
export function fetchVariablesParametersToQueryParametersString(
params: FetchVariablesParameters
): string {
return queryParamsToStr(fetchVariablesParametersToQueryParameters(params))
}
export interface IconToggleProps {
isOn: boolean
onIcon: IconDefinition
offIcon: IconDefinition
onClick: (newState: boolean) => void
}
export enum ColumnDataSourceType {
FieldDescription = "FieldDescription",
MultipleFieldDescriptions = "MultipleFieldDescriptions",
ReadOnlyColumn = "ReadOnlyColumn",
Unkown = "Unknown",
}
export interface ColumnDataSourceFieldDescription {
kind: ColumnDataSourceType.FieldDescription
description: FieldDescription
columnInformation: ColumnInformation
}
export interface ColumnDataSourceReadOnlyColumn {
kind: ColumnDataSourceType.ReadOnlyColumn
readOnlyColumn: ReadOnlyColumn
columnInformation: ColumnInformation
}
export interface ColumnDataSourceUnknown {
kind: ColumnDataSourceType.Unkown
fieldKey: string
columnInformation: ColumnInformation
}
export type ColumnDataSource =
| ColumnDataSourceFieldDescription
| ColumnDataSourceReadOnlyColumn
| ColumnDataSourceUnknown
export const IconToggleComponent = (props: IconToggleProps) => (
<button
className="btn btn-light btn-sm"
onClick={() => props.onClick(!props.isOn)}
>
<FontAwesomeIcon icon={props.isOn ? props.onIcon : props.offIcon} />
</button>
)
/** Turns a search string like "nuclear share" into a BooleanOperation
that AND connects a CONTAINS query for every word - i.e. it would result in
(AND (CONTAINS target "nuclear") (CONTAINS target "share")) */
export function searchFieldStringToFilterOperations(
searchString: string,
target: StringOperation
): BooleanOperation | undefined {
const fragments = searchString
.split(" ")
.map((item) => item.trim())
.filter((item) => item !== "")
const wordContainsParts = fragments.map(
(fragment) =>
new StringContainsOperation(target, new StringAtom(fragment))
)
if (fragments.length > 0)
return new BinaryLogicOperation(
BinaryLogicOperators.and,
wordContainsParts
)
else return undefined
}
// TODO: create a type and add the correct column names for the query
export interface ReadOnlyColumn {
label: string
key: string
type: "string" | "datetime" | "number"
sExpressionColumnTarget: string
}
export const getItemStyle = (
isDragging: boolean,
draggableStyle: any
): any => ({
userSelect: "none",
// change background colour if dragging
background: isDragging ? "lightgreen" : "inherit",
// styles we need to apply on draggables
...draggableStyle,
})
export function isConfigColumn(columnName: string): boolean {
return columnName.startsWith("/")
}
export const filterPanelInitialConfig: BasicConfig = AntdConfig
export const initialFilterQueryValue: JsonGroup = {
id: QbUtils.uuid(),
type: "group",
}
export type FilterPanelState = {
tree: ImmutableTree
config: Config
}
export function getLogicOperator(str: string): BinaryLogicOperators {
if (str === "AND") return BinaryLogicOperators.and
else if (str === "OR") return BinaryLogicOperators.or
else throw Error(`unknown logic operator: ${str}`)
}
export function getComparisonOperator(
str: string
): ComparisonOperator | undefined {
return match(str)
.with("less", () => ComparisonOperator.less)
.with("less_or_equal", () => ComparisonOperator.lessOrEqual)
.with("greater", () => ComparisonOperator.greater)
.with("greater_or_equal", () => ComparisonOperator.greaterOrEqual)
.otherwise(() => undefined)
}
export function getNullCheckOperator(
str: string
): NullCheckOperator | undefined {
return match(str)
.with("is_null", () => NullCheckOperator.isNull)
.with("is_not_null", () => NullCheckOperator.isNotNull)
.otherwise(() => undefined)
}
export function getFieldSymbol(
fieldName: string,
context: OperationContext,
readOnlyFieldNamesMap: Map<string, ReadOnlyColumn>
): Operation {
if (isConfigColumn(fieldName))
return new JsonPointerSymbol(fieldName, context)
else
return new SqlColumnName(
readOnlyFieldNamesMap.get(fieldName)!.sExpressionColumnTarget,
context
)
}
export function getValueAtom(val: any): Operation | undefined {
if (typeof val === "string") return new StringAtom(val)
else if (typeof val === "number") return new NumberAtom(val)
else if (typeof val === "boolean") return new BooleanAtom(val)
else return undefined
}
export function getEqualityOperator(str: string): EqualityOperator | undefined {
if (str === "equal" || str === "select_equals")
return EqualityOperator.equal
else if (str === "not_equal" || str === "select_not_equals")
return EqualityOperator.unequal
else return undefined
}
/** JsonLogic is the easiest format that the React Awesome Query Builder can round
trip (i.e. deserialize from). Building the internal structure of the query library
would be tedious so we convert our SExpressions to JsonLogic. */
export function SExpressionToJsonLogic(
sExpression: Operation,
readOnlyEntries: Map<string, ReadOnlyColumn>
): JSONPreciselyTyped {
return sExpression.toJsonLogic({
processSqlColumnName: (columnName) => {
const item = [...readOnlyEntries.entries()].find(
(item) => item[1].sExpressionColumnTarget === columnName
)
const mappedColumnName = item![0]
return mappedColumnName
},
})
}
/** JsonLogic is the easiest format that the React Awesome Query Library can round
trip (i.e. deserialize from). Building the internal structure of the query library
would be tedious so we convert our SExpressions to JsonLogic. When React Awesome
Query Library parses this, we need to convert some custom things like the is_latest
query operator that we added to RAQL that in our SExpressions are represented as
field = "latest"
*/
export function postprocessJsonLogicTree(filterTree: JsonTree | JsonItem) {
if (filterTree.type === "group" && filterTree.children1) {
if (
isArray(filterTree.children1) ||
checkIsPlainObjectWithGuard(filterTree.children1)
)
for (const child of Object.values(filterTree.children1))
postprocessJsonLogicTree(child)
} else if (filterTree.type === "rule") {
const {
properties: { value, operator },
} = filterTree
if (value.length !== 1) return
const isLatest = value[0] === "latest"
const isEarliest = value[0] === "earliest"
const isEqual = operator === "equal" || operator === "select_equals"
if (isLatest && isEqual) {
filterTree.properties.operator = "is_latest"
} else if (isEarliest && isEqual) {
filterTree.properties.operator = "is_earliest"
}
}
}
export function filterTreeToSExpression(
filterTree: JsonTree | JsonItem,
context: OperationContext,
readOnlyFieldNamesMap: Map<string, ReadOnlyColumn>
): Operation | undefined {
if (filterTree.type === "group") {
// If we have a group then we need to decide
// on the operator and build the list of children recursively
const logicOperator = getLogicOperator(
filterTree.properties?.conjunction ?? "AND"
)
let children: Operation[] = []
if (
isArray(filterTree.children1) ||
checkIsPlainObjectWithGuard(filterTree.children1)
)
children = excludeUndefined(
Object.values(filterTree.children1).map((child) =>
filterTreeToSExpression(
child,
context,
readOnlyFieldNamesMap
)
)
)
else if (filterTree.children1 !== undefined)
console.warn("unexpected content of children1")
if (filterTree.children1 === undefined || children.length === 0)
return undefined
const operation = new BinaryLogicOperation(logicOperator, children)
// If not is active, wrap the operation in a Negation
if (filterTree.properties?.not) return new Negation(operation)
else return operation
} else if (filterTree.type === "rule") {
if (isNil(filterTree.properties.field)) return undefined
const field = getFieldSymbol(
filterTree.properties.field,
context,
readOnlyFieldNamesMap
)
return (
match(filterTree.properties.operator)
// If we have a rule, check what operator is used and build the corresponding operation
.when(
(op) => op && getComparisonOperator(op),
(op) => {
const operator = getComparisonOperator(op as string)
if (
filterTree.properties.value.length === 0 ||
filterTree.properties.value[0] === undefined
)
return undefined
const val = getValueAtom(filterTree.properties.value[0])
return new NumericComparison(operator!, [field, val!])
}
)
.when(
(op) => op && getEqualityOperator(op),
(op) => {
const operator = getEqualityOperator(op as string)
const val = getValueAtom(filterTree.properties.value[0])
if (val === undefined) return undefined
return new EqualityComparision(operator!, [field, val])
}
)
.when(
(op) => op && op === "like",
() => {
if (
filterTree.properties.value.length === 0 ||
filterTree.properties.value[0] === undefined
)
return undefined
const val = new StringAtom(
filterTree.properties.value[0]
)
return new StringContainsOperation(field, val)
}
)
.when(
(op) => op && getNullCheckOperator(op as string),
(op) => {
const operator = getNullCheckOperator(op as string)!
return new NullCheckOperation(operator!, field)
}
)
.with("is_empty", "is_not_empty", (operator) => {
const op: EqualityOperator = match(operator)
.with("is_empty", () => EqualityOperator.equal)
.with("is_not_empty", () => EqualityOperator.unequal)
.exhaustive()
return new EqualityComparision(op, [
field,
new StringAtom(""),
])
})
.with("is_latest", (_) => {
return new EqualityComparision(EqualityOperator.equal, [
field,
new StringAtom("latest"),
])
})
.with("is_earliest", (_) => {
return new EqualityComparision(EqualityOperator.equal, [
field,
new StringAtom("earliest"),
])
})
.otherwise(() => undefined)
)
}
return undefined
}
export function simpleColumnToFilterPanelFieldConfig(
column: ReadOnlyColumn
): [string, SimpleField] {
const fieldType = match(column.type)
.with("string", () => "text")
.with("number", () => "number")
.with("datetime", () => "datetime")
.exhaustive()
return [
column.key,
{
label: column.label,
type: fieldType,
valueSources: ["value"],
excludeOperators: ["is_latest", "is_earliest"],
//preferWidgets: widget [widget],
},
]
}
export function fieldDescriptionToFilterPanelFieldConfig(
description: FieldDescription
): [string, SimpleField] | undefined {
const widget = match(description.editor)
.with(EditorOption.checkbox, () => "boolean")
.with(EditorOption.colorEditor, () => undefined)
.with(EditorOption.dropdown, () => "select")
.with(EditorOption.mappingEditor, () => undefined)
.with(EditorOption.numeric, () => "number")
.with(EditorOption.numericWithLatestEarliest, () => "number")
.with(EditorOption.primitiveListEditor, () => undefined)
.with(EditorOption.textarea, () => "text")
.with(EditorOption.textfield, () => "text")
.exhaustive()
if (widget !== undefined) {
const excludedOperators =
description.editor === EditorOption.numericWithLatestEarliest
? []
: ["is_latest", "is_earliest"]
return [
description.pointer,
{
label: description.pointer,
type: widget,
valueSources: ["value"],
//preferWidgets: widget [widget],
fieldSettings: {
listValues: description.enumOptions,
},
excludeOperators: excludedOperators,
},
]
} else return undefined
}
export function renderBuilder(props: BuilderProps) {
return (
<div className="query-builder-container" style={{ padding: "0" }}>
<div className="query-builder qb-lite">
<Builder {...props} />
</div>
</div>
)
}
export interface GrapherConfigGridEditorConfig {
source: GrapherConfigGridEditorSource
sExpressionContext: OperationContext
apiEndpoint: string
readonlyColumns: Map<string, ReadOnlyColumn>
hiddenColumns: Set<string>
columnSet: ColumnSet[]
finalVariableLayerModificationFn: (id: number) => Partial<GrapherInterface>
}
export interface GrapherConfigGridEditorProps {
config: GrapherConfigGridEditorConfig
}