forked from ukrbublik/react-awesome-query-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.js
827 lines (722 loc) · 29.4 KB
/
tree.js
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
import Immutable from "immutable";
import {
expandTreePath, expandTreeSubpath, getItemByPath, fixPathsInTree,
getTotalRulesCountInTree, fixEmptyGroupsInTree, isEmptyTree, hasChildren, removeIsLockedInTree
} from "../utils/treeUtils";
import {
defaultRuleProperties, defaultGroupProperties, defaultOperator,
defaultOperatorOptions, defaultRoot, defaultItemProperties
} from "../utils/defaultUtils";
import * as constants from "../constants";
import uuid from "../utils/uuid";
import {
getFuncConfig, getFieldConfig, getFieldWidgetConfig, getOperatorConfig
} from "../utils/configUtils";
import {
getOperatorsForField, getFirstOperator, getWidgetForFieldOp,
getNewValueForFieldOp
} from "../utils/ruleUtils";
import {deepEqual, defaultValue, applyToJS} from "../utils/stuff";
import {validateValue} from "../utils/validation";
import omit from "lodash/omit";
import mapValues from "lodash/mapValues";
/**
* @param {object} config
* @param {Immutable.List} path
* @param {Immutable.Map} properties
*/
const addNewGroup = (state, path, type, groupUuid, properties, config, children = null, meta = {}) => {
const {shouldCreateEmptyGroup} = config.settings;
const groupPath = path.push(groupUuid);
const canAddNewRule = !shouldCreateEmptyGroup;
const isDefaultCase = !!meta?.isDefaultCase;
const origState = state;
state = addItem(state, path, type, groupUuid, defaultGroupProperties(config).merge(properties || {}), config, children);
if (state !== origState) {
if (!children && !isDefaultCase) {
state = state.setIn(expandTreePath(groupPath, "children1"), new Immutable.OrderedMap());
// Add one empty rule into new group
if (canAddNewRule) {
state = addItem(state, groupPath, "rule", uuid(), defaultRuleProperties(config), config);
}
}
state = fixPathsInTree(state);
}
return state;
};
/**
* @param {object} config
* @param {Immutable.List} path
* @param {Immutable.Map} properties
*/
const removeGroup = (state, path, config) => {
state = removeItem(state, path);
const {canLeaveEmptyGroup} = config.settings;
const parentPath = path.slice(0, -1);
const isEmptyParentGroup = !hasChildren(state, parentPath);
if (isEmptyParentGroup && !canLeaveEmptyGroup) {
// check ancestors for emptiness (and delete 'em if empty)
state = fixEmptyGroupsInTree(state);
if (isEmptyTree(state) && !canLeaveEmptyGroup) {
// if whole query is empty, add one empty rule to root
state = addItem(state, new Immutable.List(), "rule", uuid(), defaultRuleProperties(config), config);
}
}
state = fixPathsInTree(state);
return state;
};
/**
* @param {object} config
* @param {Immutable.List} path
*/
const removeRule = (state, path, config) => {
state = removeItem(state, path);
const {canLeaveEmptyGroup} = config.settings;
const parentPath = path.pop();
const parent = state.getIn(expandTreePath(parentPath));
const parentField = parent.getIn(["properties", "field"]);
const parentOperator = parent.getIn(["properties", "operator"]);
const parentValue = parent.getIn(["properties", "value", 0]);
const parentFieldConfig = parentField ? getFieldConfig(config, parentField) : null;
const parentOperatorConfig = parentOperator ? getOperatorConfig(config, parentOperator, parentField) : null;
const hasGroupCountRule = parentField && parentOperator && parentOperatorConfig.cardinality != 0; // && parentValue != undefined;
const isParentRuleGroup = parent.get("type") == "rule_group";
const isEmptyParentGroup = !hasChildren(state, parentPath);
const canLeaveEmpty = isParentRuleGroup
? hasGroupCountRule && parentFieldConfig.initialEmptyWhere
: canLeaveEmptyGroup;
if (isEmptyParentGroup && !canLeaveEmpty) {
if (isParentRuleGroup) {
// deleted last rule from rule_group, so delete whole rule_group
state = state.deleteIn(expandTreePath(parentPath));
}
// check ancestors for emptiness (and delete 'em if empty)
state = fixEmptyGroupsInTree(state);
if (isEmptyTree(state) && !canLeaveEmptyGroup) {
// if whole query is empty, add one empty rule to root
state = addItem(state, new Immutable.List(), "rule", uuid(), defaultRuleProperties(config), config);
}
}
state = fixPathsInTree(state);
return state;
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {bool} not
*/
const setNot = (state, path, not) =>
state.setIn(expandTreePath(path, "properties", "not"), not);
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {bool} lock
*/
const setLock = (state, path, lock) =>
removeIsLockedInTree(state.setIn(expandTreePath(path, "properties", "isLocked"), lock));
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {string} conjunction
*/
const setConjunction = (state, path, conjunction) =>
state.setIn(expandTreePath(path, "properties", "conjunction"), conjunction);
// convert children deeply from JS to Immutable
const _addChildren1 = (config, item, children) => {
if (children && Array.isArray(children)) {
item.children1 = new Immutable.OrderedMap(
children.reduce((map, it) => {
const id1 = uuid();
const it1 = {
...it,
properties: defaultItemProperties(config, it).merge(it.properties || {}),
id: id1
};
_addChildren1(config, it1, it1.children1);
//todo: guarantee order
return {
...map,
[id1]: new Immutable.Map(it1)
};
}, {})
);
}
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {string} type
* @param {string} id
* @param {Immutable.OrderedMap} properties
* @param {object} config
*/
const addItem = (state, path, type, id, properties, config, children = null) => {
if (type == "switch_group")
throw new Error("Can't add switch_group programmatically");
const { maxNumberOfCases, maxNumberOfRules, maxNesting } = config.settings;
const rootType = state.get("type");
const isTernary = rootType == "switch_group";
const targetItem = state.getIn(expandTreePath(path));
const caseGroup = isTernary ? state.getIn(expandTreePath(path.take(2))) : null;
const childrenPath = expandTreePath(path, "children1");
const targetChildren = state.getIn(childrenPath);
const hasChildren = !!targetChildren && targetChildren.size;
const targetChildrenSize = hasChildren ? targetChildren.size : null;
let currentNumber, maxNumber;
if (type == "case_group") {
currentNumber = targetChildrenSize;
maxNumber = maxNumberOfCases;
} else if (type == "group") {
currentNumber = path.size;
maxNumber = maxNesting;
} else if (targetItem?.get("type") == "rule_group") {
// don't restrict
} else {
currentNumber = isTernary ? getTotalRulesCountInTree(caseGroup) : getTotalRulesCountInTree(state);
maxNumber = maxNumberOfRules;
}
const canAdd = maxNumber && currentNumber ? (currentNumber < maxNumber) : true;
const item = {type, id, properties};
_addChildren1(config, item, children);
const isLastDefaultCase = type == "case_group" && hasChildren && targetChildren.last().get("children1") == null;
if (canAdd) {
const newChildren = new Immutable.OrderedMap({
[id]: new Immutable.Map(item)
});
if (!hasChildren) {
state = state.setIn(childrenPath, newChildren);
} else if (isLastDefaultCase) {
const last = targetChildren.last();
const newChildrenWithLast = new Immutable.OrderedMap({
[id]: new Immutable.Map(item),
[last.get("id")]: last
});
state = state.deleteIn(expandTreePath(childrenPath, "children1", last.get("id")));
state = state.mergeIn(childrenPath, newChildrenWithLast);
} else {
state = state.mergeIn(childrenPath, newChildren);
}
state = fixPathsInTree(state);
}
return state;
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
*/
const removeItem = (state, path) => {
state = state.deleteIn(expandTreePath(path));
state = fixPathsInTree(state);
return state;
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} fromPath
* @param {Immutable.List} toPath
* @param {string} placement, see constants PLACEMENT_*: PLACEMENT_AFTER, PLACEMENT_BEFORE, PLACEMENT_APPEND, PLACEMENT_PREPEND
* @param {object} config
*/
const moveItem = (state, fromPath, toPath, placement, config) => {
const from = getItemByPath(state, fromPath);
const sourcePath = fromPath.pop();
const source = fromPath.size > 1 ? getItemByPath(state, sourcePath) : null;
const sourceChildren = source ? source.get("children1") : null;
const to = getItemByPath(state, toPath);
const targetPath = (placement == constants.PLACEMENT_APPEND || placement == constants.PLACEMENT_PREPEND) ? toPath : toPath.pop();
const target = (placement == constants.PLACEMENT_APPEND || placement == constants.PLACEMENT_PREPEND)
? to
: toPath.size > 1 ? getItemByPath(state, targetPath) : null;
const targetChildren = target ? target.get("children1") : null;
if (!source || !target)
return state;
const isSameParent = (source.get("id") == target.get("id"));
const isSourceInsideTarget = targetPath.size < sourcePath.size
&& deepEqual(targetPath.toArray(), sourcePath.toArray().slice(0, targetPath.size));
const isTargetInsideSource = targetPath.size > sourcePath.size
&& deepEqual(sourcePath.toArray(), targetPath.toArray().slice(0, sourcePath.size));
let sourceSubpathFromTarget = null;
let targetSubpathFromSource = null;
if (isSourceInsideTarget) {
sourceSubpathFromTarget = Immutable.List(sourcePath.toArray().slice(targetPath.size));
} else if (isTargetInsideSource) {
targetSubpathFromSource = Immutable.List(targetPath.toArray().slice(sourcePath.size));
}
let newTargetChildren = targetChildren, newSourceChildren = sourceChildren;
if (!isTargetInsideSource)
newSourceChildren = newSourceChildren.delete(from.get("id"));
if (isSameParent) {
newTargetChildren = newSourceChildren;
} else if (isSourceInsideTarget) {
newTargetChildren = newTargetChildren.updateIn(expandTreeSubpath(sourceSubpathFromTarget, "children1"), (_oldChildren) => newSourceChildren);
}
if (placement == constants.PLACEMENT_BEFORE || placement == constants.PLACEMENT_AFTER) {
newTargetChildren = Immutable.OrderedMap().withMutations(r => {
for (let [itemId, item] of newTargetChildren.entries()) {
if (itemId == to.get("id") && placement == constants.PLACEMENT_BEFORE) {
r.set(from.get("id"), from);
}
r.set(itemId, item);
if (itemId == to.get("id") && placement == constants.PLACEMENT_AFTER) {
r.set(from.get("id"), from);
}
}
});
} else if (placement == constants.PLACEMENT_APPEND) {
newTargetChildren = newTargetChildren.merge({[from.get("id")]: from});
} else if (placement == constants.PLACEMENT_PREPEND) {
newTargetChildren = Immutable.OrderedMap({[from.get("id")]: from}).merge(newTargetChildren);
}
if (isTargetInsideSource) {
newSourceChildren = newSourceChildren.updateIn(expandTreeSubpath(targetSubpathFromSource, "children1"), (_oldChildren) => newTargetChildren);
newSourceChildren = newSourceChildren.delete(from.get("id"));
}
if (!isSameParent && !isSourceInsideTarget)
state = state.updateIn(expandTreePath(sourcePath, "children1"), (_oldChildren) => newSourceChildren);
if (!isTargetInsideSource)
state = state.updateIn(expandTreePath(targetPath, "children1"), (_oldChildren) => newTargetChildren);
state = fixPathsInTree(state);
return state;
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {string} field
*/
const setField = (state, path, newField, config) => {
if (!newField)
return removeItem(state, path);
const {fieldSeparator, setOpOnChangeField, showErrorMessage} = config.settings;
if (Array.isArray(newField))
newField = newField.join(fieldSeparator);
const currentType = state.getIn(expandTreePath(path, "type"));
const currentProperties = state.getIn(expandTreePath(path, "properties"));
const wasRuleGroup = currentType == "rule_group";
const newFieldConfig = getFieldConfig(config, newField);
const isRuleGroup = newFieldConfig.type == "!group";
const isRuleGroupExt = isRuleGroup && newFieldConfig.mode == "array";
const isChangeToAnotherType = wasRuleGroup != isRuleGroup;
const currentOperator = currentProperties.get("operator");
const currentOperatorOptions = currentProperties.get("operatorOptions");
const _currentField = currentProperties.get("field");
const _currentValue = currentProperties.get("value");
const _currentValueSrc = currentProperties.get("valueSrc", new Immutable.List());
const _currentValueType = currentProperties.get("valueType", new Immutable.List());
// If the newly selected field supports the same operator the rule currently
// uses, keep it selected.
const lastOp = newFieldConfig && newFieldConfig.operators.indexOf(currentOperator) !== -1 ? currentOperator : null;
let newOperator = null;
const availOps = getOperatorsForField(config, newField);
if (availOps && availOps.length == 1)
newOperator = availOps[0];
else if (availOps && availOps.length > 1) {
for (let strategy of setOpOnChangeField || []) {
if (strategy == "keep" && !isChangeToAnotherType)
newOperator = lastOp;
else if (strategy == "default")
newOperator = defaultOperator(config, newField, false);
else if (strategy == "first")
newOperator = getFirstOperator(config, newField);
if (newOperator) //found op for strategy
break;
}
}
if (!isRuleGroup && !newFieldConfig.operators) {
console.warn(`Type ${newFieldConfig.type} is not supported`);
return state;
}
if (wasRuleGroup && !isRuleGroup) {
state = state.setIn(expandTreePath(path, "type"), "rule");
state = state.deleteIn(expandTreePath(path, "children1"));
state = state.setIn(expandTreePath(path, "properties"), new Immutable.OrderedMap());
}
if (isRuleGroup) {
state = state.setIn(expandTreePath(path, "type"), "rule_group");
const {canReuseValue, newValue, newValueSrc, newValueType, operatorCardinality} = getNewValueForFieldOp(
config, config, currentProperties, newField, newOperator, "field", true
);
let groupProperties = defaultGroupProperties(config, newFieldConfig).merge({
field: newField,
mode: newFieldConfig.mode,
});
if (isRuleGroupExt) {
groupProperties = groupProperties.merge({
operator: newOperator,
value: newValue,
valueSrc: newValueSrc,
valueType: newValueType,
});
}
state = state.setIn(expandTreePath(path, "children1"), new Immutable.OrderedMap());
state = state.setIn(expandTreePath(path, "properties"), groupProperties);
if (newFieldConfig.initialEmptyWhere && operatorCardinality == 1) { // just `COUNT(grp) > 1` without `HAVING ..`
// no childeren
} else {
state = addItem(state, path, "rule", uuid(), defaultRuleProperties(config, newField), config);
}
state = fixPathsInTree(state);
return state;
}
return state.updateIn(expandTreePath(path, "properties"), (map) => map.withMutations((current) => {
const {canReuseValue, newValue, newValueSrc, newValueType, newValueError} = getNewValueForFieldOp(
config, config, current, newField, newOperator, "field", true
);
if (showErrorMessage) {
current = current
.set("valueError", newValueError);
}
const newOperatorOptions = canReuseValue ? currentOperatorOptions : defaultOperatorOptions(config, newOperator, newField);
return current
.set("field", newField)
.set("operator", newOperator)
.set("operatorOptions", newOperatorOptions)
.set("value", newValue)
.set("valueSrc", newValueSrc)
.set("valueType", newValueType)
.delete("asyncListValues");
}));
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {string} operator
*/
const setOperator = (state, path, newOperator, config) => {
const {showErrorMessage} = config.settings;
const properties = state.getIn(expandTreePath(path, "properties"));
const children = state.getIn(expandTreePath(path, "children1"));
const currentField = properties.get("field");
const fieldConfig = getFieldConfig(config, currentField);
const isRuleGroup = fieldConfig.type == "!group";
const operatorConfig = getOperatorConfig(config, newOperator, currentField);
const operatorCardinality = operatorConfig ? defaultValue(operatorConfig.cardinality, 1) : null;
state = state.updateIn(expandTreePath(path, "properties"), (map) => map.withMutations((current) => {
const currentField = current.get("field");
const currentOperatorOptions = current.get("operatorOptions");
const _currentValue = current.get("value", new Immutable.List());
const _currentValueSrc = current.get("valueSrc", new Immutable.List());
const _currentOperator = current.get("operator");
const {canReuseValue, newValue, newValueSrc, newValueType, newValueError} = getNewValueForFieldOp(
config, config, current, currentField, newOperator, "operator", true
);
if (showErrorMessage) {
current = current
.set("valueError", newValueError);
}
const newOperatorOptions = canReuseValue ? currentOperatorOptions : defaultOperatorOptions(config, newOperator, currentField);
if (!canReuseValue) {
current = current
.delete("asyncListValues");
}
return current
.set("operator", newOperator)
.set("operatorOptions", newOperatorOptions)
.set("value", newValue)
.set("valueSrc", newValueSrc)
.set("valueType", newValueType);
}));
if (isRuleGroup) {
if (operatorCardinality == 0 && children.size == 0) {
state = addItem(state, path, "rule", uuid(), defaultRuleProperties(config, currentField), config);
}
}
return state;
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {integer} delta
* @param {*} value
* @param {string} valueType
* @param {*} asyncListValues
* @param {boolean} __isInternal
*/
const setValue = (state, path, delta, value, valueType, config, asyncListValues, __isInternal) => {
const {fieldSeparator, showErrorMessage} = config.settings;
let isInternalValueChange;
const valueSrc = state.getIn(expandTreePath(path, "properties", "valueSrc", delta + "")) || null;
if (valueSrc === "field" && Array.isArray(value))
value = value.join(fieldSeparator);
const field = state.getIn(expandTreePath(path, "properties", "field")) || null;
const operator = state.getIn(expandTreePath(path, "properties", "operator")) || null;
const operatorConfig = getOperatorConfig(config, operator, field);
const operatorCardinality = operator ? defaultValue(operatorConfig.cardinality, 1) : null;
const isEndValue = false;
const canFix = false;
const calculatedValueType = valueType || calculateValueType(value, valueSrc, config);
const [validateError, fixedValue] = validateValue(
config, field, field, operator, value, calculatedValueType, valueSrc, asyncListValues, canFix, isEndValue
);
const isValid = !validateError;
if (isValid && fixedValue !== value) {
// eg, get exact value from listValues (not string)
value = fixedValue;
}
// Additional validation for range values
if (showErrorMessage) {
const w = getWidgetForFieldOp(config, field, operator, valueSrc);
const fieldWidgetDefinition = getFieldWidgetConfig(config, field, operator, w, valueSrc);
const valueSrcs = Array.from({length: operatorCardinality}, (_, i) => (state.getIn(expandTreePath(path, "properties", "valueSrc", i + "")) || null));
if (operatorConfig && operatorConfig.validateValues && valueSrcs.filter(vs => vs == "value" || vs == null).length == operatorCardinality) {
const values = Array.from({length: operatorCardinality}, (_, i) => (i == delta ? value : state.getIn(expandTreePath(path, "properties", "value", i + "")) || null));
const jsValues = fieldWidgetDefinition && fieldWidgetDefinition.toJS ? values.map(v => fieldWidgetDefinition.toJS(v, fieldWidgetDefinition)) : values;
const rangeValidateError = operatorConfig.validateValues(jsValues);
state = state.setIn(expandTreePath(path, "properties", "valueError", operatorCardinality), rangeValidateError);
}
}
const lastValueArr = state.getIn(expandTreePath(path, "properties", "value"));
if (!lastValueArr) {
state = state
.setIn(expandTreePath(path, "properties", "value"), new Immutable.List(new Array(operatorCardinality)))
.setIn(expandTreePath(path, "properties", "valueType"), new Immutable.List(new Array(operatorCardinality)))
.setIn(expandTreePath(path, "properties", "valueError"), new Immutable.List(new Array(operatorCardinality)));
}
const lastValue = state.getIn(expandTreePath(path, "properties", "value", delta + ""));
const lastError = state.getIn(expandTreePath(path, "properties", "valueError", delta));
const isLastEmpty = lastValue == undefined;
const isLastError = !!lastError;
if (isValid || showErrorMessage) {
state = state.deleteIn(expandTreePath(path, "properties", "asyncListValues"));
// set only good value
if (typeof value === "undefined") {
state = state.setIn(expandTreePath(path, "properties", "value", delta + ""), undefined);
state = state.setIn(expandTreePath(path, "properties", "valueType", delta + ""), null);
} else {
if (asyncListValues) {
state = state.setIn(expandTreePath(path, "properties", "asyncListValues"), asyncListValues);
}
state = state.setIn(expandTreePath(path, "properties", "value", delta + ""), value);
state = state.setIn(expandTreePath(path, "properties", "valueType", delta + ""), calculatedValueType);
isInternalValueChange = __isInternal && !isLastEmpty && !isLastError;
}
}
if (showErrorMessage) {
state = state.setIn(expandTreePath(path, "properties", "valueError", delta), validateError);
}
if (__isInternal && (isValid && isLastError || !isValid && !isLastError)) {
state = state.setIn(expandTreePath(path, "properties", "valueError", delta), validateError);
isInternalValueChange = false;
}
return {tree: state, isInternalValueChange};
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {integer} delta
* @param {*} srcKey
*/
const setValueSrc = (state, path, delta, srcKey, config) => {
const {showErrorMessage} = config.settings;
const field = state.getIn(expandTreePath(path, "properties", "field")) || null;
const operator = state.getIn(expandTreePath(path, "properties", "operator")) || null;
state = state.setIn(expandTreePath(path, "properties", "value", delta + ""), undefined);
state = state.setIn(expandTreePath(path, "properties", "valueType", delta + ""), null);
state = state.deleteIn(expandTreePath(path, "properties", "asyncListValues"));
if (showErrorMessage) {
// clear value error
state = state.setIn(expandTreePath(path, "properties", "valueError", delta), null);
// if current operator is range, clear possible range error
const operatorConfig = getOperatorConfig(config, operator, field);
const operatorCardinality = operator ? defaultValue(operatorConfig.cardinality, 1) : null;
if (operatorConfig.validateValues) {
state = state.setIn(expandTreePath(path, "properties", "valueError", operatorCardinality), null);
}
}
// set valueSrc
if (typeof srcKey === "undefined") {
state = state.setIn(expandTreePath(path, "properties", "valueSrc", delta + ""), null);
} else {
state = state.setIn(expandTreePath(path, "properties", "valueSrc", delta + ""), srcKey);
}
// maybe set default value
if (srcKey) {
const properties = state.getIn(expandTreePath(path, "properties"));
// this call should return canReuseValue = false and provide default value
const {canReuseValue, newValue, newValueSrc, newValueType, newValueError} = getNewValueForFieldOp(
config, config, properties, field, operator, "valueSrc", true
);
if (!canReuseValue && newValueSrc.get(delta) == srcKey) {
state = state.setIn(expandTreePath(path, "properties", "value", delta + ""), newValue.get(delta));
state = state.setIn(expandTreePath(path, "properties", "valueType", delta + ""), newValueType.get(delta));
}
}
return state;
};
/**
* @param {Immutable.Map} state
* @param {Immutable.List} path
* @param {string} name
* @param {*} value
*/
const setOperatorOption = (state, path, name, value) => {
return state.setIn(expandTreePath(path, "properties", "operatorOptions", name), value);
};
/**
* @param {Immutable.Map} state
*/
const checkEmptyGroups = (state, config) => {
const {canLeaveEmptyGroup} = config.settings;
if (!canLeaveEmptyGroup) {
state = fixEmptyGroupsInTree(state);
}
return state;
};
/**
*
*/
const calculateValueType = (value, valueSrc, config) => {
let calculatedValueType = null;
if (value) {
if (valueSrc === "field") {
const fieldConfig = getFieldConfig(config, value);
if (fieldConfig) {
calculatedValueType = fieldConfig.type;
}
} else if (valueSrc === "func") {
const funcKey = value.get("func");
if (funcKey) {
const funcConfig = getFuncConfig(config, funcKey);
if (funcConfig) {
calculatedValueType = funcConfig.returnType;
}
}
}
}
return calculatedValueType;
};
const getField = (state, path) => {
const field = state.getIn(expandTreePath(path, "properties", "field")) || null;
return field;
};
const emptyDrag = {
dragging: {
id: null,
x: null,
y: null,
w: null,
h: null
},
mousePos: {},
dragStart: {
id: null,
},
};
const getActionMeta = (action, state) => {
const actionKeysToOmit = [
"config", "asyncListValues", "__isInternal"
];
const actionTypesToIgnore = [
constants.SET_TREE,
constants.SET_DRAG_START,
constants.SET_DRAG_PROGRESS,
constants.SET_DRAG_END,
];
let meta = mapValues(omit(action, actionKeysToOmit), applyToJS);
let affectedField = action.path && getField(state.tree, action.path) || action.field;
if (affectedField)
meta.affectedField = affectedField;
if (actionTypesToIgnore.includes(action.type) || action.type.indexOf("@@redux") == 0)
meta = null;
return meta;
};
/**
* @param {Immutable.Map} state
* @param {object} action
*/
export default (config) => {
const emptyTree = defaultRoot(config);
const emptyState = Object.assign({}, {tree: emptyTree}, emptyDrag);
return (state = emptyState, action) => {
const unset = {__isInternalValueChange: undefined, __lastAction: undefined};
let set = {};
let actionMeta = getActionMeta(action, state);
switch (action.type) {
case constants.SET_TREE: {
set.tree = action.tree;
break;
}
case constants.ADD_CASE_GROUP: {
set.tree = addNewGroup(state.tree, action.path, "case_group", action.id, action.properties, action.config, action.children, action.meta);
break;
}
case constants.ADD_GROUP: {
set.tree = addNewGroup(state.tree, action.path, "group", action.id, action.properties, action.config, action.children, action.meta);
break;
}
case constants.REMOVE_GROUP: {
set.tree = removeGroup(state.tree, action.path, action.config);
break;
}
case constants.ADD_RULE: {
set.tree = addItem(state.tree, action.path, action.ruleType, action.id, action.properties, action.config, action.children);
break;
}
case constants.REMOVE_RULE: {
set.tree = removeRule(state.tree, action.path, action.config);
break;
}
case constants.SET_CONJUNCTION: {
set.tree = setConjunction(state.tree, action.path, action.conjunction);
break;
}
case constants.SET_NOT: {
set.tree = setNot(state.tree, action.path, action.not);
break;
}
case constants.SET_FIELD: {
set.tree = setField(state.tree, action.path, action.field, action.config);
break;
}
case constants.SET_LOCK: {
set.tree = setLock(state.tree, action.path, action.lock);
break;
}
case constants.SET_OPERATOR: {
set.tree = setOperator(state.tree, action.path, action.operator, action.config);
break;
}
case constants.SET_VALUE: {
const {tree, isInternalValueChange} = setValue(
state.tree, action.path, action.delta, action.value, action.valueType, action.config, action.asyncListValues, action.__isInternal
);
set.__isInternalValueChange = isInternalValueChange;
set.tree = tree;
break;
}
case constants.SET_VALUE_SRC: {
set.tree = setValueSrc(state.tree, action.path, action.delta, action.srcKey, action.config);
break;
}
case constants.SET_OPERATOR_OPTION: {
set.tree = setOperatorOption(state.tree, action.path, action.name, action.value);
break;
}
case constants.MOVE_ITEM: {
set.tree = moveItem(state.tree, action.fromPath, action.toPath, action.placement, action.config);
break;
}
case constants.SET_DRAG_START: {
set.dragStart = action.dragStart;
set.dragging = action.dragging;
set.mousePos = action.mousePos;
break;
}
case constants.SET_DRAG_PROGRESS: {
set.mousePos = action.mousePos;
set.dragging = action.dragging;
break;
}
case constants.SET_DRAG_END: {
set.tree = checkEmptyGroups(state.tree, config);
set = { ...set, ...emptyDrag };
break;
}
default: {
break;
}
}
if (actionMeta) {
set.__lastAction = actionMeta;
}
return {...state, ...unset, ...set};
};
};