PromucFlow_constructor/app/client/src/utils/DynamicBindingUtils.ts

511 lines
16 KiB
TypeScript
Raw Normal View History

2019-11-06 06:35:15 +00:00
import _ from "lodash";
2019-11-25 05:07:27 +00:00
import { WidgetProps } from "widgets/BaseWidget";
import {
DATA_BIND_REGEX,
DATA_BIND_REGEX_GLOBAL,
} from "constants/BindingsConstants";
2019-11-19 12:44:58 +00:00
import ValidationFactory from "./ValidationFactory";
2020-02-18 10:41:52 +00:00
import JSExecutionManagerSingleton, {
JSExecutorResult,
} from "jsExecution/JSExecutionManagerSingleton";
2020-01-08 10:50:49 +00:00
import unescapeJS from "unescape-js";
2020-01-17 09:28:26 +00:00
import toposort from "toposort";
2020-02-18 10:41:52 +00:00
import {
DataTree,
DataTreeAction,
DataTreeEntity,
2020-02-18 10:41:52 +00:00
DataTreeWidget,
ENTITY_TYPE,
} from "entities/DataTree/dataTreeFactory";
2020-03-23 12:40:17 +00:00
import * as log from "loglevel";
import equal from "fast-deep-equal/es6";
2019-12-06 13:16:08 +00:00
2020-01-27 13:53:33 +00:00
export const removeBindingsFromObject = (obj: object) => {
const string = JSON.stringify(obj);
const withBindings = string.replace(DATA_BIND_REGEX_GLOBAL, "{{ }}");
2020-01-27 13:53:33 +00:00
return JSON.parse(withBindings);
};
// referencing DATA_BIND_REGEX fails for the value "{{Table1.tableData[Table1.selectedRowIndex]}}" if you run it multiple times and don't recreate
2019-11-14 09:28:51 +00:00
export const isDynamicValue = (value: string): boolean =>
2019-12-02 07:37:33 +00:00
DATA_BIND_REGEX.test(value);
2019-11-28 03:56:44 +00:00
//{{}}{{}}}
2019-12-02 09:51:18 +00:00
export function parseDynamicString(dynamicString: string): string[] {
2019-11-28 03:56:44 +00:00
let parsedDynamicValues = [];
const indexOfDoubleParanStart = dynamicString.indexOf("{{");
if (indexOfDoubleParanStart === -1) {
return [dynamicString];
}
//{{}}{{}}}
const firstString = dynamicString.substring(0, indexOfDoubleParanStart);
firstString && parsedDynamicValues.push(firstString);
let rest = dynamicString.substring(
indexOfDoubleParanStart,
dynamicString.length,
);
//{{}}{{}}}
let sum = 0;
for (let i = 0; i <= rest.length - 1; i++) {
const char = rest[i];
const prevChar = rest[i - 1];
if (char === "{") {
sum++;
} else if (char === "}") {
sum--;
if (prevChar === "}" && sum === 0) {
parsedDynamicValues.push(rest.substring(0, i + 1));
rest = rest.substring(i + 1, rest.length);
if (rest) {
parsedDynamicValues = parsedDynamicValues.concat(
parseDynamicString(rest),
);
break;
}
}
}
}
if (sum !== 0 && dynamicString !== "") {
return [dynamicString];
}
return parsedDynamicValues;
}
2019-11-14 09:28:51 +00:00
2020-01-17 09:28:26 +00:00
const getAllPaths = (
tree: Record<string, any>,
prefix = "",
): Record<string, true> => {
return Object.keys(tree).reduce((res: Record<string, true>, el): Record<
string,
true
> => {
if (Array.isArray(tree[el])) {
const key = `${prefix}${el}`;
return { ...res, [key]: true };
} else if (typeof tree[el] === "object" && tree[el] !== null) {
const key = `${prefix}${el}`;
return { ...res, [key]: true, ...getAllPaths(tree[el], `${key}.`) };
} else {
const key = `${prefix}${el}`;
return { ...res, [key]: true };
}
}, {});
};
2019-11-14 09:28:51 +00:00
export const getDynamicBindings = (
dynamicString: string,
): { mustaches: string[]; jsSnippets: string[] } => {
2020-03-06 09:45:21 +00:00
// Protect against bad string parse
if (!dynamicString || !_.isString(dynamicString)) {
return { mustaches: [], jsSnippets: [] };
2020-03-06 09:45:21 +00:00
}
2020-01-17 09:28:26 +00:00
const sanitisedString = dynamicString.trim();
2019-11-14 09:28:51 +00:00
// Get the {{binding}} bound values
2020-01-17 09:28:26 +00:00
const bindings = parseDynamicString(sanitisedString);
2019-11-14 09:28:51 +00:00
// Get the "binding" path values
2019-11-28 03:56:44 +00:00
const paths = bindings.map(binding => {
const length = binding.length;
const matches = isDynamicValue(binding);
2019-11-28 03:56:44 +00:00
if (matches) {
return binding.substring(2, length - 2);
}
2019-11-14 09:28:51 +00:00
return "";
});
return { mustaches: bindings, jsSnippets: paths };
2019-11-14 09:28:51 +00:00
};
2019-11-06 06:35:15 +00:00
// Paths are expected to have "{name}.{path}" signature
2020-02-18 10:41:52 +00:00
// Also returns any action triggers found after evaluating value
export const evaluateDynamicBoundValue = (
2020-02-18 10:41:52 +00:00
data: DataTree,
2019-11-06 06:35:15 +00:00
path: string,
2020-02-18 10:41:52 +00:00
callbackData?: any,
): JSExecutorResult => {
2020-01-08 10:50:49 +00:00
const unescapedInput = unescapeJS(path);
2020-02-18 10:41:52 +00:00
return JSExecutionManagerSingleton.evaluateSync(
unescapedInput,
data,
callbackData,
);
2019-11-14 09:28:51 +00:00
};
// For creating a final value where bindings could be in a template format
export const createDynamicValueString = (
binding: string,
subBindings: string[],
subValues: string[],
): string => {
// Replace the string with the data tree values
let finalValue = binding;
subBindings.forEach((b, i) => {
let value = subValues[i];
if (Array.isArray(value) || _.isObject(value)) {
value = JSON.stringify(value);
}
finalValue = finalValue.replace(b, value);
});
return finalValue;
};
export const getDynamicValue = (
dynamicBinding: string,
2020-02-18 10:41:52 +00:00
data: DataTree,
callBackData?: any,
includeTriggers = false,
): JSExecutorResult => {
2019-11-14 09:28:51 +00:00
// Get the {{binding}} bound values
const { mustaches, jsSnippets } = getDynamicBindings(dynamicBinding);
if (mustaches.length) {
2019-11-14 09:28:51 +00:00
// Get the Data Tree value of those "binding "paths
const values = jsSnippets.map((jsSnippet, index) => {
if (jsSnippet) {
const result = evaluateDynamicBoundValue(data, jsSnippet, callBackData);
2020-02-18 10:41:52 +00:00
if (includeTriggers) {
return result;
} else {
return { result: result.result };
}
2019-12-30 07:39:53 +00:00
} else {
return { result: mustaches[index], triggers: [] };
2019-12-30 07:39:53 +00:00
}
2019-11-28 03:56:44 +00:00
});
2019-11-14 09:28:51 +00:00
// if it is just one binding, no need to create template string
if (mustaches.length === 1) return values[0];
2019-11-14 09:28:51 +00:00
// else return a string template with bindings
2020-02-18 10:41:52 +00:00
const templateString = createDynamicValueString(
dynamicBinding,
mustaches,
2020-02-18 10:41:52 +00:00
values.map(v => v.result),
);
return {
result: templateString,
};
2019-11-14 09:28:51 +00:00
}
2020-02-18 10:41:52 +00:00
return { result: undefined, triggers: [] };
2019-11-06 06:35:15 +00:00
};
export const getValidatedTree = (tree: any) => {
2020-01-17 09:28:26 +00:00
return Object.keys(tree).reduce((tree, entityKey: string) => {
const entity = tree[entityKey];
if (entity && entity.type) {
const parsedEntity = { ...entity };
Object.keys(entity).forEach((property: string) => {
const value = entity[property];
// Pass it through parse
const {
parsed,
isValid,
message,
} = ValidationFactory.validateWidgetProperty(
2020-01-17 09:28:26 +00:00
entity.type,
property,
value,
2020-03-31 03:21:35 +00:00
entity,
2020-01-17 09:28:26 +00:00
);
parsedEntity[property] = parsed;
if (!isValid) {
_.set(parsedEntity, `invalidProps.${property}`, true);
_.set(parsedEntity, `validationMessages.${property}`, message);
}
2020-01-17 09:28:26 +00:00
});
return { ...tree, [entityKey]: parsedEntity };
}
return tree;
}, tree);
};
// let dynamicDependencyMapCache: Array<[string, string]> = [];
// let oldDataTree: DataTree = {};
//
// let dataTreeCache: DataTree = {};
// let lastCacheTime = 0;
2020-03-23 12:40:17 +00:00
export function getEvaluatedDataTree(dataTree: DataTree): DataTree {
// count total time taken
const totalStart = performance.now();
// Dont evaluate if called again in 60 ms
// if (totalStart - lastCacheTime < 60) {
// return dataTreeCache;
// }
// lastCacheTime = totalStart;
2020-03-23 12:40:17 +00:00
// const cleanDataTree = _.omit(dataTree, [
// ...dataTree.actionPaths,
// "__proto__",
// ]);
// const isCacheHit = equal(oldDataTree, cleanDataTree);
// oldDataTree = cleanDataTree;
// log.debug("dependencyTree cacheHit " + isCacheHit);
2020-03-23 12:40:17 +00:00
// Create Dependencies DAG
const createDepsStart = performance.now();
const dynamicDependencyMap = createDependencyTree(dataTree);
// dynamicDependencyMapCache = dynamicDependencyMap;
const createDepsEnd = performance.now();
2020-03-23 12:40:17 +00:00
// Evaluate Tree
const evaluatedTreeStart = performance.now();
const evaluatedTree = dependencySortedEvaluateDataTree(
dataTree,
dynamicDependencyMap,
);
const evaluatedTreeEnd = performance.now();
2020-03-23 12:40:17 +00:00
// Set Loading Widgets
const loadingTreeStart = performance.now();
const treeWithLoading = setTreeLoading(evaluatedTree, dynamicDependencyMap);
const loadingTreeEnd = performance.now();
2020-03-23 12:40:17 +00:00
// Validate Widgets
const validated = getValidatedTree(treeWithLoading);
// End counting total time
const endStart = performance.now();
// Log time taken and count
const timeTaken = {
total: (endStart - totalStart).toFixed(2),
createDeps: (createDepsEnd - createDepsStart).toFixed(2),
evaluate: (evaluatedTreeEnd - evaluatedTreeStart).toFixed(2),
loading: (loadingTreeEnd - loadingTreeStart).toFixed(2),
2020-03-23 12:40:17 +00:00
};
log.debug("data tree evaluated");
log.debug(timeTaken);
// dataTreeCache = validated;
return validated;
2020-03-23 12:40:17 +00:00
}
2020-01-17 09:28:26 +00:00
type DynamicDependencyMap = Record<string, Array<string>>;
export const createDependencyTree = (
2020-02-18 10:41:52 +00:00
dataTree: DataTree,
2020-01-17 09:28:26 +00:00
): Array<[string, string]> => {
const dependencyMap: DynamicDependencyMap = {};
const allKeys = getAllPaths(dataTree);
Object.keys(dataTree).forEach(entityKey => {
const entity = dataTree[entityKey] as WidgetProps;
if (entity && entity.dynamicBindings) {
Object.keys(entity.dynamicBindings).forEach(prop => {
const { jsSnippets } = getDynamicBindings(entity[prop]);
dependencyMap[`${entityKey}.${prop}`] = jsSnippets.filter(
jsSnippet => !!jsSnippet,
);
2020-01-17 09:28:26 +00:00
});
}
});
Object.keys(dependencyMap).forEach(key => {
dependencyMap[key] = _.flatten(
dependencyMap[key].map(path => calculateSubDependencies(path, allKeys)),
);
});
const dependencyTree: Array<[string, string]> = [];
Object.keys(dependencyMap).forEach((key: string) => {
2020-02-03 11:49:20 +00:00
if (dependencyMap[key].length) {
dependencyMap[key].forEach(dep => dependencyTree.push([key, dep]));
} else {
// Set no dependency
dependencyTree.push([key, ""]);
}
2020-01-17 09:28:26 +00:00
});
return dependencyTree;
};
const calculateSubDependencies = (
path: string,
all: Record<string, true>,
): Array<string> => {
const subDeps: Array<string> = [];
const identifiers = path.match(/[a-zA-Z_$][a-zA-Z_$0-9.]*/g) || [path];
identifiers.forEach((identifier: string) => {
if (identifier in all) {
subDeps.push(identifier);
} else {
const subIdentifiers =
identifier.match(/[a-zA-Z_$][a-zA-Z_$0-9]*/g) || [];
let current = "";
for (let i = 0; i < subIdentifiers.length; i++) {
const key = `${current}${current ? "." : ""}${subIdentifiers[i]}`;
if (key in all) {
current = key;
} else {
break;
}
}
if (current) subDeps.push(current);
}
});
return subDeps;
};
2020-01-30 13:23:04 +00:00
export const setTreeLoading = (
2020-02-18 10:41:52 +00:00
dataTree: DataTree,
2020-01-30 13:23:04 +00:00
dependencyMap: Array<[string, string]>,
) => {
Object.keys(dataTree)
2020-02-18 10:41:52 +00:00
.filter(e => {
const entity = dataTree[e] as DataTreeAction;
return entity.ENTITY_TYPE === ENTITY_TYPE.ACTION && entity.isLoading;
})
2020-01-30 13:23:04 +00:00
.reduce(
(allEntities: string[], curr) =>
allEntities.concat(getEntityDependencies(dependencyMap, curr)),
[],
)
2020-02-18 10:41:52 +00:00
.forEach(w => {
const entity = dataTree[w] as DataTreeWidget;
2020-02-18 10:41:52 +00:00
entity.isLoading = true;
});
return dataTree;
2020-01-30 13:23:04 +00:00
};
export const getEntityDependencies = (
dependencyMap: Array<[string, string]>,
entity: string,
): Array<string> => {
const entityDeps: Record<string, string[]> = dependencyMap
.map(d => [d[1].split(".")[0], d[0].split(".")[0]])
.filter(d => d[0] !== d[1])
.reduce((deps: Record<string, string[]>, dep) => {
const key: string = dep[0];
const value: string = dep[1];
return {
...deps,
[key]: deps[key] ? deps[key].concat(value) : [value],
};
}, {});
if (entity in entityDeps) {
const recFind = (
keys: Array<string>,
deps: Record<string, string[]>,
): Array<string> => {
let allDeps: string[] = [];
keys.forEach(e => {
allDeps = allDeps.concat([e]);
if (e in deps) {
allDeps = allDeps.concat([...recFind(deps[e], deps)]);
}
});
return allDeps;
};
return recFind(entityDeps[entity], entityDeps);
}
return [];
};
const cache: Map<string, any> = new Map();
const dependencyCache: Map<string, any[]> = new Map();
2020-01-17 09:28:26 +00:00
export function dependencySortedEvaluateDataTree(
2020-02-18 10:41:52 +00:00
dataTree: DataTree,
2020-01-17 09:28:26 +00:00
dependencyTree: Array<[string, string]>,
2020-02-18 10:41:52 +00:00
): DataTree {
2020-01-27 13:53:33 +00:00
const tree = _.cloneDeep(dataTree);
2020-01-17 09:28:26 +00:00
try {
2020-02-03 11:49:20 +00:00
// sort dependencies and remove empty dependencies
2020-03-23 12:40:17 +00:00
const sortStart = performance.now();
2020-02-03 11:49:20 +00:00
const sortedDependencies = toposort(dependencyTree)
.reverse()
.filter(d => !!d);
2020-03-23 12:40:17 +00:00
const sortEnd = performance.now();
2020-01-17 09:28:26 +00:00
// evaluate and replace values
2020-03-23 12:40:17 +00:00
const evalStart = performance.now();
const dependencyMap: any = {};
dependencyTree.forEach(dependencyArr => {
const propertyPath = dependencyArr[0];
if (dependencyMap[propertyPath]) {
dependencyMap[propertyPath].push(dependencyArr[1]);
} else {
dependencyMap[propertyPath] = [dependencyArr[1]];
}
});
2020-03-23 12:40:17 +00:00
const final = sortedDependencies.reduce(
(currentTree: DataTree, propertyPath: string) => {
const entityName = propertyPath.split(".")[0];
2020-03-23 12:40:17 +00:00
const entity: DataTreeEntity = currentTree[entityName];
let unEvalPropertyValue = _.get(currentTree as any, propertyPath);
let evalPropertyValue = unEvalPropertyValue;
const requiresEval = isDynamicValue(unEvalPropertyValue);
if (requiresEval) {
2020-03-23 12:40:17 +00:00
try {
const propertyDependencies = dependencyMap[propertyPath];
const currentDependencyValues = propertyDependencies
? propertyDependencies
.map((path: string) => {
//*** Remove current path from data tree because cached value contains evaluated version while this contains unevaluated version */
const cleanDataTree = _.omit(currentTree, [propertyPath]);
return _.get(cleanDataTree, path);
})
.filter((data: any) => {
return data !== undefined;
})
: undefined;
const cachedDependencyValues = dependencyCache.get(propertyPath);
const cacheObj = cache.get(propertyPath);
const isCacheHit =
cacheObj &&
equal(cacheObj.unEvalVal, unEvalPropertyValue) &&
cachedDependencyValues !== undefined &&
equal(currentDependencyValues, cachedDependencyValues);
if (isCacheHit) {
evalPropertyValue = cacheObj.evalVal;
} else {
log.debug("eval " + propertyPath);
const dynamicResult = getDynamicValue(
unEvalPropertyValue,
currentTree,
);
evalPropertyValue = dynamicResult.result;
cache.set(propertyPath, {
evalVal: evalPropertyValue,
unEvalVal: unEvalPropertyValue,
});
dependencyCache.set(propertyPath, currentDependencyValues);
evalPropertyValue = dynamicResult.result;
}
2020-03-23 12:40:17 +00:00
} catch (e) {
console.error(e);
evalPropertyValue = undefined;
unEvalPropertyValue = undefined;
2020-03-23 12:40:17 +00:00
}
2020-03-03 06:51:59 +00:00
}
2020-03-23 12:40:17 +00:00
if (
"ENTITY_TYPE" in entity &&
entity.ENTITY_TYPE === ENTITY_TYPE.WIDGET
) {
const propertyName = propertyPath.split(".")[1];
2020-03-23 12:40:17 +00:00
const {
parsed,
isValid,
message,
} = ValidationFactory.validateWidgetProperty(
entity.type,
propertyName,
evalPropertyValue,
2020-03-31 03:21:35 +00:00
entity,
2020-03-23 12:40:17 +00:00
);
evalPropertyValue = parsed;
2020-03-23 12:40:17 +00:00
if (!isValid) {
_.set(entity, `invalidProps.${propertyName}`, true);
_.set(entity, `validationMessages.${propertyName}`, message);
2020-03-23 12:40:17 +00:00
}
}
return _.set(currentTree, propertyPath, evalPropertyValue);
2020-03-23 12:40:17 +00:00
},
tree,
);
const evalEnd = performance.now();
log.debug({
depLength: sortedDependencies.length,
sort: (sortEnd - sortStart).toFixed(2),
eval: (evalEnd - evalStart).toFixed(2),
});
return final;
2020-01-17 09:28:26 +00:00
} catch (e) {
console.error(e);
return tree;
}
}