-
-
Notifications
You must be signed in to change notification settings - Fork 505
/
Copy pathutils.tsx
86 lines (77 loc) · 2.7 KB
/
utils.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
import React, { useEffect } from "react";
import {
Utils,
ImmutableTree, Config, JsonTree, JsonLogicTree, SanitizeOptions, Actions
} from "@react-awesome-query-builder/ui";
import { SqlUtils } from "@react-awesome-query-builder/sql";
import { initFiles } from "./init_data";
// Trick for HMR
export const dispatchHmrUpdate = (loadedConfig: Config, initTree: ImmutableTree) => {
const updateEvent = new CustomEvent<CustomEventDetail>("update", { detail: {
config: loadedConfig,
initTree: initTree,
} });
window.dispatchEvent(updateEvent);
};
export interface CustomEventDetail {
config: Config;
initTree: ImmutableTree;
}
export const useHmrUpdate = (callback: (detail: CustomEventDetail) => void) => {
useEffect(() => {
window.addEventListener("update", onHotUpdate);
return () => {
window.removeEventListener("update", onHotUpdate);
};
});
const onHotUpdate = (e: Event) => {
const {detail} = e as CustomEvent<CustomEventDetail>;
console.log("Updating...");
callback(detail);
};
};
////////
export const importFromInitFile = (fileKey: string, config?: Config) => {
const fileType = fileKey.split("/")[0];
let tree: ImmutableTree | undefined;
let errors: string[] = [];
if (fileType === "logic") {
const initLogic = initFiles[fileKey] as JsonLogicTree;
tree = Utils.loadFromJsonLogic(initLogic, config);
} else if (fileType === "sql") {
const initValue = initFiles[fileKey] as string;
({tree, errors} = SqlUtils.loadFromSql(initValue, config));
} else if (fileType === "spel") {
const initValue = initFiles[fileKey] as string;
[tree, errors] = Utils.loadFromSpel(initValue, config);
} else if (fileType === "tree") {
const initValue = initFiles[fileKey] as JsonTree;
tree = Utils.loadTree(initValue);
} else {
throw new Error(`Unknown file type ${fileType}`);
}
if (errors.length) {
console.warn(`Errors while importing from ${fileKey} as ${fileType}:`, errors);
}
return {tree, errors};
};
export const initTreeWithValidation = (initFileKey: string, config: Config, validationOptions?: Partial<SanitizeOptions>) => {
let tree: ImmutableTree;
let errors: string[];
// eslint-disable-next-line prefer-const
({tree, errors} = importFromInitFile(initFileKey, config));
const {fixedTree, fixedErrors, nonFixedErrors} = Utils.sanitizeTree(tree, config, {
...(validationOptions ?? {}),
removeEmptyGroups: false,
removeEmptyRules: false,
removeIncompleteRules: false,
});
tree = fixedTree;
if (fixedErrors.length) {
console.warn("Fixed tree errors on load: ", fixedErrors);
}
if (nonFixedErrors.length) {
console.warn("Validation errors on load:", nonFixedErrors);
}
return {tree, errors};
};