PromucFlow_constructor/app/client/src/workers/evaluationUtils.ts

924 lines
27 KiB
TypeScript
Raw Normal View History

2021-01-29 06:04:28 +00:00
import {
DependencyMap,
EVAL_ERROR_PATH,
EvaluationError,
getEvalErrorPath,
getEvalValuePath,
2021-01-29 06:04:28 +00:00
isChildPropertyPath,
isDynamicValue,
PropertyEvaluationErrorType,
2021-02-22 11:14:08 +00:00
} from "utils/DynamicBindingUtils";
import { validate } from "./validations";
import { Diff } from "deep-diff";
import {
DataTree,
2021-01-29 06:04:28 +00:00
DataTreeAction,
2021-07-20 10:02:56 +00:00
DataTreeAppsmith,
DataTreeEntity,
DataTreeWidget,
ENTITY_TYPE,
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
DataTreeJSAction,
EvaluationSubstitutionType,
PrivateWidgets,
2021-02-22 11:14:08 +00:00
} from "entities/DataTree/dataTreeFactory";
import _ from "lodash";
import { WidgetTypeConfigMap } from "utils/WidgetFactory";
import { ValidationConfig } from "constants/PropertyControlConstants";
import { Severity } from "entities/AppsmithConsole";
import { ParsedBody, ParsedJSSubAction } from "utils/JSPaneUtils";
import { Variable } from "entities/JSCollection";
import { PluginType } from "entities/Action";
const clone = require("rfdc/default");
import { warn as logWarn } from "loglevel";
2021-01-29 06:04:28 +00:00
// Dropdown1.options[1].value -> Dropdown1.options[1]
// Dropdown1.options[1] -> Dropdown1.options
// Dropdown1.options -> Dropdown1
export const IMMEDIATE_PARENT_REGEX = /^(.*)(\..*|\[.*\])$/;
export enum DataTreeDiffEvent {
NEW = "NEW",
DELETE = "DELETE",
EDIT = "EDIT",
NOOP = "NOOP",
}
export type DataTreeDiff = {
payload: {
propertyPath: string;
value?: string;
};
event: DataTreeDiffEvent;
};
export class CrashingError extends Error {}
export const convertPathToString = (arrPath: Array<string | number>) => {
let string = "";
arrPath.forEach((segment) => {
if (isInt(segment)) {
string = string + "[" + segment + "]";
} else {
if (string.length !== 0) {
string = string + ".";
}
string = string + segment;
}
});
return string;
};
// Todo: improve the logic here
// Right now NaN, Infinity, floats, everything works
function isInt(val: string | number): boolean {
return Number.isInteger(val) || (_.isString(val) && /^\d+$/.test(val));
}
// Removes the entity name from the property path
export function getEntityNameAndPropertyPath(
fullPath: string,
): {
entityName: string;
propertyPath: string;
} {
const indexOfFirstDot = fullPath.indexOf(".");
if (indexOfFirstDot === -1) {
// No dot was found so path is the entity name itself
return {
entityName: fullPath,
propertyPath: "",
};
}
const entityName = fullPath.substring(0, indexOfFirstDot);
const propertyPath = fullPath.substring(indexOfFirstDot + 1);
return { entityName, propertyPath };
}
//these paths are not required to go through evaluate tree as these are internal properties
const ignorePathsForEvalRegex =
".(bindingPaths|triggerPaths|validationPaths|dynamicBindingPathList)";
//match if paths are part of ignorePathsForEvalRegex
const isUninterestingChangeForDependencyUpdate = (path: string) => {
return path.match(ignorePathsForEvalRegex);
};
export const translateDiffEventToDataTreeDiffEvent = (
difference: Diff<any, any>,
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
unEvalDataTree: DataTree,
): DataTreeDiff | DataTreeDiff[] => {
let result: DataTreeDiff | DataTreeDiff[] = {
payload: {
propertyPath: "",
value: "",
},
event: DataTreeDiffEvent.NOOP,
};
if (!difference.path) {
return result;
}
const propertyPath = convertPathToString(difference.path);
//we do not need evaluate these paths coz these are internal paths
const isUninterestingPathForUpdateTree = isUninterestingChangeForDependencyUpdate(
propertyPath,
);
if (!!isUninterestingPathForUpdateTree) {
return result;
}
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
const { entityName } = getEntityNameAndPropertyPath(propertyPath);
const entity = unEvalDataTree[entityName];
const isJsAction = isJSAction(entity);
switch (difference.kind) {
case "N": {
result.event = DataTreeDiffEvent.NEW;
result.payload = {
propertyPath,
};
break;
}
case "D": {
result.event = DataTreeDiffEvent.DELETE;
result.payload = { propertyPath };
break;
}
case "E": {
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
let rhsChange, lhsChange;
if (isJsAction) {
rhsChange = typeof difference.rhs === "string";
lhsChange = typeof difference.lhs === "string";
} else {
rhsChange =
typeof difference.rhs === "string" && isDynamicValue(difference.rhs);
lhsChange =
typeof difference.lhs === "string" && isDynamicValue(difference.lhs);
}
if (rhsChange || lhsChange) {
result.event = DataTreeDiffEvent.EDIT;
result.payload = {
propertyPath,
value: difference.rhs,
};
} else if (difference.lhs === undefined || difference.rhs === undefined) {
// Handle static value changes that change structure that can lead to
// old bindings being eligible
if (difference.lhs === undefined && isTrueObject(difference.rhs)) {
result.event = DataTreeDiffEvent.NEW;
result.payload = { propertyPath };
}
if (difference.rhs === undefined && isTrueObject(difference.lhs)) {
result.event = DataTreeDiffEvent.DELETE;
result.payload = { propertyPath };
}
} else if (
isTrueObject(difference.lhs) &&
!isTrueObject(difference.rhs)
) {
// This will happen for static value changes where a property went
// from being an object to any other type like string or number
// in such a case we want to delete all nested paths of the
// original lhs object
result = Object.keys(difference.lhs).map((diffKey) => {
const path = `${propertyPath}.${diffKey}`;
return {
event: DataTreeDiffEvent.DELETE,
payload: {
propertyPath: path,
},
};
});
} else if (
!isTrueObject(difference.lhs) &&
isTrueObject(difference.rhs)
) {
// This will happen for static value changes where a property went
// from being any other type like string or number to an object
// in such a case we want to add all nested paths of the
// new rhs object
result = Object.keys(difference.rhs).map((diffKey) => {
const path = `${propertyPath}.${diffKey}`;
return {
event: DataTreeDiffEvent.NEW,
payload: {
propertyPath: path,
},
};
});
}
break;
}
case "A": {
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
return translateDiffEventToDataTreeDiffEvent(
{
...difference.item,
path: [...difference.path, difference.index],
},
unEvalDataTree,
);
}
default: {
break;
}
}
return result;
};
/*
Table1.selectedRow
Table1.selectedRow.email: ["Input1.defaultText"]
*/
export const addDependantsOfNestedPropertyPaths = (
parentPaths: Array<string>,
inverseMap: DependencyMap,
): Set<string> => {
const withNestedPaths: Set<string> = new Set();
const dependantNodes = Object.keys(inverseMap);
parentPaths.forEach((propertyPath) => {
withNestedPaths.add(propertyPath);
dependantNodes
.filter((dependantNodePath) =>
2021-01-29 06:04:28 +00:00
isChildPropertyPath(propertyPath, dependantNodePath),
)
.forEach((dependantNodePath) => {
inverseMap[dependantNodePath].forEach((path) => {
withNestedPaths.add(path);
});
});
});
return withNestedPaths;
};
2021-01-29 06:04:28 +00:00
export function isWidget(entity: DataTreeEntity): entity is DataTreeWidget {
return (
typeof entity === "object" &&
"ENTITY_TYPE" in entity &&
entity.ENTITY_TYPE === ENTITY_TYPE.WIDGET
);
}
2021-01-29 06:04:28 +00:00
export function isAction(entity: DataTreeEntity): entity is DataTreeAction {
return (
typeof entity === "object" &&
"ENTITY_TYPE" in entity &&
entity.ENTITY_TYPE === ENTITY_TYPE.ACTION
);
}
2021-07-20 10:02:56 +00:00
export function isAppsmithEntity(
entity: DataTreeEntity,
): entity is DataTreeAppsmith {
return (
typeof entity === "object" &&
"ENTITY_TYPE" in entity &&
entity.ENTITY_TYPE === ENTITY_TYPE.APPSMITH
);
}
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
export function isJSAction(entity: DataTreeEntity): entity is DataTreeJSAction {
return (
typeof entity === "object" &&
"ENTITY_TYPE" in entity &&
entity.ENTITY_TYPE === ENTITY_TYPE.JSACTION
);
}
export function isJSObject(entity: DataTreeEntity): entity is DataTreeJSAction {
return (
typeof entity === "object" &&
"ENTITY_TYPE" in entity &&
entity.ENTITY_TYPE === ENTITY_TYPE.JSACTION &&
"pluginType" in entity &&
entity.pluginType === PluginType.JS
);
}
// We need to remove functions from data tree to avoid any unexpected identifier while JSON parsing
// Check issue https://github.com/appsmithorg/appsmith/issues/719
export const removeFunctions = (value: any) => {
if (_.isFunction(value)) {
return "Function call";
} else if (_.isObject(value)) {
return JSON.parse(
JSON.stringify(value, (_, v) =>
typeof v === "bigint" ? v.toString() : v,
),
);
} else {
return value;
}
};
export const makeParentsDependOnChildren = (
depMap: DependencyMap,
allkeys: Record<string, true>,
): DependencyMap => {
//return depMap;
// Make all parents depend on child
Object.keys(depMap).forEach((key) => {
depMap = makeParentsDependOnChild(depMap, key, allkeys);
depMap[key].forEach((path) => {
depMap = makeParentsDependOnChild(depMap, path, allkeys);
});
});
return depMap;
};
2021-01-29 06:04:28 +00:00
export const makeParentsDependOnChild = (
depMap: DependencyMap,
child: string,
allkeys: Record<string, true>,
): DependencyMap => {
const result: DependencyMap = depMap;
let curKey = child;
if (!allkeys[curKey]) {
logWarn(
`makeParentsDependOnChild - ${curKey} is not present in dataTree.`,
"This might result in a cyclic dependency.",
);
}
let matches: Array<string> | null;
// Note: The `=` is intentional
// Stops looping when match is null
2021-01-29 06:04:28 +00:00
while ((matches = curKey.match(IMMEDIATE_PARENT_REGEX)) !== null) {
const parentKey = matches[1];
// Todo: switch everything to set.
const existing = new Set(result[parentKey] || []);
existing.add(curKey);
result[parentKey] = Array.from(existing);
curKey = parentKey;
}
return result;
};
2021-01-29 06:04:28 +00:00
// The idea is to find the immediate parents of the property paths
// e.g. For Table1.selectedRow.email, the parent is Table1.selectedRow
export const getImmediateParentsOfPropertyPaths = (
propertyPaths: Array<string>,
): Array<string> => {
// Use a set to ensure that we dont have duplicates
const parents: Set<string> = new Set();
propertyPaths.forEach((path) => {
const matches = path.match(IMMEDIATE_PARENT_REGEX);
if (matches !== null) {
parents.add(matches[1]);
}
});
return Array.from(parents);
};
export function validateWidgetProperty(
config: ValidationConfig,
value: unknown,
props: Record<string, unknown>,
feat: JSON Form widget (#8472) * initial layout * updated parser to support nested array * array field rendering * changes * ts fix * minor revert FormWidget * modified schema structure * select and switch fields * added checkbox field * added RadioGroupField * partial DateField and defaults, typing refactoring * added label and field type change * minor ts changes * changes * modified widget/utils for nested panelConfig, modified schema to object approach * array/object label support * hide field configuration when children not present * added tooltip * field visibility option * disabled state * upgraded tslib, form initial values * custom field configuration - add/hide/edit * field configuration - label change * return input when field configuration reaches max depth * minor changes * form - scroll, fixedfooter, enitity defn and other minior changes * form title * unregister on unmount * fixes * zero state * fix field padding * patched updating form values, removed linting warnings * configured action buttons * minor fix * minor change * property pane - sort fields in field configuration * refactor include all properties * checkbox properties * date properties * refactor typings and radio group properties * switch, multselect, select, array, object properties * minor changes * default value * ts fixes * checkbox field properties implementation * date field prop implementation * switch field * select field and fix deep nested meta properties * multiselect implementation * minor change * input field implementation * fix position jump on field type change * initial accordian * field state property and auto-complete of JSONFormComputeControl * merge fixes * renamed FormBuilder to JSONForm * source data validation minor change * custom field default value fix * Editable keys for custom field * minor fixes * replaced useFieldArray with custom logic, added widget icon * array and object accordian with border/background styling * minor change * disabled states for array and objects * default value minor fix * form level styles * modified logic for isDisabled for array and object, added disabledWhenInvalid, exposed isValid to fieldState for text input, removed useDisableChildren * added isValid for all field types * fixed reset to default values * debounce form values update * minor change * minor change * fix crash - source data change multi-select to array, fix crash - change of options * fix positioning * detect date type in source data * fix crash - when object is passed to regex input field * fixed default sourceData path for fields * accodion keep children mounted on collapse * jest test for schemaParser * widget/helper and useRegisterFieldInvalid test * tests for property config helper and generatePanelPropertyConfig * fix input field validation not appearing * fix date field type detection * rename data -> formData * handle null/undefined field value change in sourceData * added null/undefined as valid values for defaultValue text field * auto detect email field * set formData default value on initial load * switch field inline positioning * field margin fix for row direction * select full width * fiex date field default value - out of range * fix any field type to array * array default value logic change * base cypress test changes * initial json form render cy test * key sanitization * fix fieldState update logic * required design, object/array background color, accordion changes, fix - add new custom field * minor change * cypress tests * fix date formatted value, field state cypress test * cypress - field properties test and fixes * rename test file * fix accessort change to blank value, cypress tests * fix array field default value for modified accessor * minor fix * added animate loading * fix empty state, add new custom field * test data fix * fix warnings * fix timePrecision visibility * button styling * ported input v2 * fix jest tests * fix cypress tests * perf changes * perf improvement * added comments * multiselect changes * input field perf refactor * array field, object field refactor performance * checkbox field refactor * refectored date, radio, select and switch * fixes * test fixes * fixes * minor fix * rename field renderer * remove tracked fieldRenderer field * cypress test fixes * cypress changes * array default value fixes * arrayfield passedDefaultValue * auto enabled JS mode for few properties, reverted swith and date property controls * cypress changes * added widget sniping mode and fixed object passedDefaultValue * multiselect v2 * select v2 * fix jest tests * test fixes * field limit * rename field type dropdown texts * field type changes fixes * jest fixes * loading state submit button * default source data for new widget * modify limit message * multiseelct default value changes and cypress fix * select default value * keep default value intact on field type change * TextTable cypress text fix * review changes * fixed footer changes * collapse styles section by default * fixed footer changes * form modes * custom field key rentention * fixed footer fix in view mode * non ascii characters * fix meta merge in dataTreeWidget * minor fixes * rename useRegisterFieldInvalid.ts -> useRegisterFieldValidity.ts * modified dependency injection into evaluated values * refactored fixedfooter logic * minor change * accessor update * minor change * fixes * QA fixes date field, scroll content * fix phone number field, removed visiblity option from array item * fix sourceData autocomplete * reset logic * fix multiselect reset * form values hydration on widget drag * code review changes * reverted order of merge dataTreeWidget * fixes * added button titles, fixed hydration issue * default value fixes * upgraded react hook form, modified array-level/field-level default value logic * fixed select validation * added icon entity explorer, modified icon align control * modify accessor validation for mongo db _id * update email field regex * review changes * explicitly handle empty source data validation
2022-03-24 07:13:25 +00:00
propertyPath: string,
) {
if (!config) {
return {
isValid: true,
parsed: value,
};
}
feat: JSON Form widget (#8472) * initial layout * updated parser to support nested array * array field rendering * changes * ts fix * minor revert FormWidget * modified schema structure * select and switch fields * added checkbox field * added RadioGroupField * partial DateField and defaults, typing refactoring * added label and field type change * minor ts changes * changes * modified widget/utils for nested panelConfig, modified schema to object approach * array/object label support * hide field configuration when children not present * added tooltip * field visibility option * disabled state * upgraded tslib, form initial values * custom field configuration - add/hide/edit * field configuration - label change * return input when field configuration reaches max depth * minor changes * form - scroll, fixedfooter, enitity defn and other minior changes * form title * unregister on unmount * fixes * zero state * fix field padding * patched updating form values, removed linting warnings * configured action buttons * minor fix * minor change * property pane - sort fields in field configuration * refactor include all properties * checkbox properties * date properties * refactor typings and radio group properties * switch, multselect, select, array, object properties * minor changes * default value * ts fixes * checkbox field properties implementation * date field prop implementation * switch field * select field and fix deep nested meta properties * multiselect implementation * minor change * input field implementation * fix position jump on field type change * initial accordian * field state property and auto-complete of JSONFormComputeControl * merge fixes * renamed FormBuilder to JSONForm * source data validation minor change * custom field default value fix * Editable keys for custom field * minor fixes * replaced useFieldArray with custom logic, added widget icon * array and object accordian with border/background styling * minor change * disabled states for array and objects * default value minor fix * form level styles * modified logic for isDisabled for array and object, added disabledWhenInvalid, exposed isValid to fieldState for text input, removed useDisableChildren * added isValid for all field types * fixed reset to default values * debounce form values update * minor change * minor change * fix crash - source data change multi-select to array, fix crash - change of options * fix positioning * detect date type in source data * fix crash - when object is passed to regex input field * fixed default sourceData path for fields * accodion keep children mounted on collapse * jest test for schemaParser * widget/helper and useRegisterFieldInvalid test * tests for property config helper and generatePanelPropertyConfig * fix input field validation not appearing * fix date field type detection * rename data -> formData * handle null/undefined field value change in sourceData * added null/undefined as valid values for defaultValue text field * auto detect email field * set formData default value on initial load * switch field inline positioning * field margin fix for row direction * select full width * fiex date field default value - out of range * fix any field type to array * array default value logic change * base cypress test changes * initial json form render cy test * key sanitization * fix fieldState update logic * required design, object/array background color, accordion changes, fix - add new custom field * minor change * cypress tests * fix date formatted value, field state cypress test * cypress - field properties test and fixes * rename test file * fix accessort change to blank value, cypress tests * fix array field default value for modified accessor * minor fix * added animate loading * fix empty state, add new custom field * test data fix * fix warnings * fix timePrecision visibility * button styling * ported input v2 * fix jest tests * fix cypress tests * perf changes * perf improvement * added comments * multiselect changes * input field perf refactor * array field, object field refactor performance * checkbox field refactor * refectored date, radio, select and switch * fixes * test fixes * fixes * minor fix * rename field renderer * remove tracked fieldRenderer field * cypress test fixes * cypress changes * array default value fixes * arrayfield passedDefaultValue * auto enabled JS mode for few properties, reverted swith and date property controls * cypress changes * added widget sniping mode and fixed object passedDefaultValue * multiselect v2 * select v2 * fix jest tests * test fixes * field limit * rename field type dropdown texts * field type changes fixes * jest fixes * loading state submit button * default source data for new widget * modify limit message * multiseelct default value changes and cypress fix * select default value * keep default value intact on field type change * TextTable cypress text fix * review changes * fixed footer changes * collapse styles section by default * fixed footer changes * form modes * custom field key rentention * fixed footer fix in view mode * non ascii characters * fix meta merge in dataTreeWidget * minor fixes * rename useRegisterFieldInvalid.ts -> useRegisterFieldValidity.ts * modified dependency injection into evaluated values * refactored fixedfooter logic * minor change * accessor update * minor change * fixes * QA fixes date field, scroll content * fix phone number field, removed visiblity option from array item * fix sourceData autocomplete * reset logic * fix multiselect reset * form values hydration on widget drag * code review changes * reverted order of merge dataTreeWidget * fixes * added button titles, fixed hydration issue * default value fixes * upgraded react hook form, modified array-level/field-level default value logic * fixed select validation * added icon entity explorer, modified icon align control * modify accessor validation for mongo db _id * update email field regex * review changes * explicitly handle empty source data validation
2022-03-24 07:13:25 +00:00
return validate(config, value, props, propertyPath);
}
export function validateActionProperty(
config: ValidationConfig,
value: unknown,
) {
if (!config) {
return {
isValid: true,
parsed: value,
};
}
feat: JSON Form widget (#8472) * initial layout * updated parser to support nested array * array field rendering * changes * ts fix * minor revert FormWidget * modified schema structure * select and switch fields * added checkbox field * added RadioGroupField * partial DateField and defaults, typing refactoring * added label and field type change * minor ts changes * changes * modified widget/utils for nested panelConfig, modified schema to object approach * array/object label support * hide field configuration when children not present * added tooltip * field visibility option * disabled state * upgraded tslib, form initial values * custom field configuration - add/hide/edit * field configuration - label change * return input when field configuration reaches max depth * minor changes * form - scroll, fixedfooter, enitity defn and other minior changes * form title * unregister on unmount * fixes * zero state * fix field padding * patched updating form values, removed linting warnings * configured action buttons * minor fix * minor change * property pane - sort fields in field configuration * refactor include all properties * checkbox properties * date properties * refactor typings and radio group properties * switch, multselect, select, array, object properties * minor changes * default value * ts fixes * checkbox field properties implementation * date field prop implementation * switch field * select field and fix deep nested meta properties * multiselect implementation * minor change * input field implementation * fix position jump on field type change * initial accordian * field state property and auto-complete of JSONFormComputeControl * merge fixes * renamed FormBuilder to JSONForm * source data validation minor change * custom field default value fix * Editable keys for custom field * minor fixes * replaced useFieldArray with custom logic, added widget icon * array and object accordian with border/background styling * minor change * disabled states for array and objects * default value minor fix * form level styles * modified logic for isDisabled for array and object, added disabledWhenInvalid, exposed isValid to fieldState for text input, removed useDisableChildren * added isValid for all field types * fixed reset to default values * debounce form values update * minor change * minor change * fix crash - source data change multi-select to array, fix crash - change of options * fix positioning * detect date type in source data * fix crash - when object is passed to regex input field * fixed default sourceData path for fields * accodion keep children mounted on collapse * jest test for schemaParser * widget/helper and useRegisterFieldInvalid test * tests for property config helper and generatePanelPropertyConfig * fix input field validation not appearing * fix date field type detection * rename data -> formData * handle null/undefined field value change in sourceData * added null/undefined as valid values for defaultValue text field * auto detect email field * set formData default value on initial load * switch field inline positioning * field margin fix for row direction * select full width * fiex date field default value - out of range * fix any field type to array * array default value logic change * base cypress test changes * initial json form render cy test * key sanitization * fix fieldState update logic * required design, object/array background color, accordion changes, fix - add new custom field * minor change * cypress tests * fix date formatted value, field state cypress test * cypress - field properties test and fixes * rename test file * fix accessort change to blank value, cypress tests * fix array field default value for modified accessor * minor fix * added animate loading * fix empty state, add new custom field * test data fix * fix warnings * fix timePrecision visibility * button styling * ported input v2 * fix jest tests * fix cypress tests * perf changes * perf improvement * added comments * multiselect changes * input field perf refactor * array field, object field refactor performance * checkbox field refactor * refectored date, radio, select and switch * fixes * test fixes * fixes * minor fix * rename field renderer * remove tracked fieldRenderer field * cypress test fixes * cypress changes * array default value fixes * arrayfield passedDefaultValue * auto enabled JS mode for few properties, reverted swith and date property controls * cypress changes * added widget sniping mode and fixed object passedDefaultValue * multiselect v2 * select v2 * fix jest tests * test fixes * field limit * rename field type dropdown texts * field type changes fixes * jest fixes * loading state submit button * default source data for new widget * modify limit message * multiseelct default value changes and cypress fix * select default value * keep default value intact on field type change * TextTable cypress text fix * review changes * fixed footer changes * collapse styles section by default * fixed footer changes * form modes * custom field key rentention * fixed footer fix in view mode * non ascii characters * fix meta merge in dataTreeWidget * minor fixes * rename useRegisterFieldInvalid.ts -> useRegisterFieldValidity.ts * modified dependency injection into evaluated values * refactored fixedfooter logic * minor change * accessor update * minor change * fixes * QA fixes date field, scroll content * fix phone number field, removed visiblity option from array item * fix sourceData autocomplete * reset logic * fix multiselect reset * form values hydration on widget drag * code review changes * reverted order of merge dataTreeWidget * fixes * added button titles, fixed hydration issue * default value fixes * upgraded react hook form, modified array-level/field-level default value logic * fixed select validation * added icon entity explorer, modified icon align control * modify accessor validation for mongo db _id * update email field regex * review changes * explicitly handle empty source data validation
2022-03-24 07:13:25 +00:00
return validate(config, value, {}, "");
}
export function getValidatedTree(tree: DataTree) {
return Object.keys(tree).reduce((tree, entityKey: string) => {
const entity = tree[entityKey] as DataTreeWidget;
if (!isWidget(entity)) {
return tree;
}
const parsedEntity = { ...entity };
Object.entries(entity.validationPaths).forEach(([property, validation]) => {
const value = _.get(entity, property);
// Pass it through parse
const { isValid, messages, parsed, transformed } = validateWidgetProperty(
validation,
value,
entity,
feat: JSON Form widget (#8472) * initial layout * updated parser to support nested array * array field rendering * changes * ts fix * minor revert FormWidget * modified schema structure * select and switch fields * added checkbox field * added RadioGroupField * partial DateField and defaults, typing refactoring * added label and field type change * minor ts changes * changes * modified widget/utils for nested panelConfig, modified schema to object approach * array/object label support * hide field configuration when children not present * added tooltip * field visibility option * disabled state * upgraded tslib, form initial values * custom field configuration - add/hide/edit * field configuration - label change * return input when field configuration reaches max depth * minor changes * form - scroll, fixedfooter, enitity defn and other minior changes * form title * unregister on unmount * fixes * zero state * fix field padding * patched updating form values, removed linting warnings * configured action buttons * minor fix * minor change * property pane - sort fields in field configuration * refactor include all properties * checkbox properties * date properties * refactor typings and radio group properties * switch, multselect, select, array, object properties * minor changes * default value * ts fixes * checkbox field properties implementation * date field prop implementation * switch field * select field and fix deep nested meta properties * multiselect implementation * minor change * input field implementation * fix position jump on field type change * initial accordian * field state property and auto-complete of JSONFormComputeControl * merge fixes * renamed FormBuilder to JSONForm * source data validation minor change * custom field default value fix * Editable keys for custom field * minor fixes * replaced useFieldArray with custom logic, added widget icon * array and object accordian with border/background styling * minor change * disabled states for array and objects * default value minor fix * form level styles * modified logic for isDisabled for array and object, added disabledWhenInvalid, exposed isValid to fieldState for text input, removed useDisableChildren * added isValid for all field types * fixed reset to default values * debounce form values update * minor change * minor change * fix crash - source data change multi-select to array, fix crash - change of options * fix positioning * detect date type in source data * fix crash - when object is passed to regex input field * fixed default sourceData path for fields * accodion keep children mounted on collapse * jest test for schemaParser * widget/helper and useRegisterFieldInvalid test * tests for property config helper and generatePanelPropertyConfig * fix input field validation not appearing * fix date field type detection * rename data -> formData * handle null/undefined field value change in sourceData * added null/undefined as valid values for defaultValue text field * auto detect email field * set formData default value on initial load * switch field inline positioning * field margin fix for row direction * select full width * fiex date field default value - out of range * fix any field type to array * array default value logic change * base cypress test changes * initial json form render cy test * key sanitization * fix fieldState update logic * required design, object/array background color, accordion changes, fix - add new custom field * minor change * cypress tests * fix date formatted value, field state cypress test * cypress - field properties test and fixes * rename test file * fix accessort change to blank value, cypress tests * fix array field default value for modified accessor * minor fix * added animate loading * fix empty state, add new custom field * test data fix * fix warnings * fix timePrecision visibility * button styling * ported input v2 * fix jest tests * fix cypress tests * perf changes * perf improvement * added comments * multiselect changes * input field perf refactor * array field, object field refactor performance * checkbox field refactor * refectored date, radio, select and switch * fixes * test fixes * fixes * minor fix * rename field renderer * remove tracked fieldRenderer field * cypress test fixes * cypress changes * array default value fixes * arrayfield passedDefaultValue * auto enabled JS mode for few properties, reverted swith and date property controls * cypress changes * added widget sniping mode and fixed object passedDefaultValue * multiselect v2 * select v2 * fix jest tests * test fixes * field limit * rename field type dropdown texts * field type changes fixes * jest fixes * loading state submit button * default source data for new widget * modify limit message * multiseelct default value changes and cypress fix * select default value * keep default value intact on field type change * TextTable cypress text fix * review changes * fixed footer changes * collapse styles section by default * fixed footer changes * form modes * custom field key rentention * fixed footer fix in view mode * non ascii characters * fix meta merge in dataTreeWidget * minor fixes * rename useRegisterFieldInvalid.ts -> useRegisterFieldValidity.ts * modified dependency injection into evaluated values * refactored fixedfooter logic * minor change * accessor update * minor change * fixes * QA fixes date field, scroll content * fix phone number field, removed visiblity option from array item * fix sourceData autocomplete * reset logic * fix multiselect reset * form values hydration on widget drag * code review changes * reverted order of merge dataTreeWidget * fixes * added button titles, fixed hydration issue * default value fixes * upgraded react hook form, modified array-level/field-level default value logic * fixed select validation * added icon entity explorer, modified icon align control * modify accessor validation for mongo db _id * update email field regex * review changes * explicitly handle empty source data validation
2022-03-24 07:13:25 +00:00
property,
);
_.set(parsedEntity, property, parsed);
const evaluatedValue = isValid
? parsed
: _.isUndefined(transformed)
? value
: transformed;
const safeEvaluatedValue = removeFunctions(evaluatedValue);
_.set(
parsedEntity,
getEvalValuePath(`${entityKey}.${property}`, false),
safeEvaluatedValue,
);
if (!isValid) {
const evalErrors: EvaluationError[] =
messages?.map((message) => ({
errorType: PropertyEvaluationErrorType.VALIDATION,
errorMessage: message,
severity: Severity.ERROR,
raw: value,
})) ?? [];
addErrorToEntityProperty(
evalErrors,
tree,
getEvalErrorPath(`${entityKey}.${property}`, false),
);
}
});
return { ...tree, [entityKey]: parsedEntity };
}, tree);
}
2021-01-29 17:59:23 +00:00
export const getAllPaths = (
records: any,
curKey = "",
result: Record<string, true> = {},
): Record<string, true> => {
// Add the key if it exists
if (curKey) result[curKey] = true;
if (Array.isArray(records)) {
for (let i = 0; i < records.length; i++) {
const tempKey = curKey ? `${curKey}[${i}]` : `${i}`;
getAllPaths(records[i], tempKey, result);
}
} else if (typeof records === "object") {
for (const key in records) {
const tempKey = curKey ? `${curKey}.${key}` : `${key}`;
getAllPaths(records[key], tempKey, result);
}
}
return result;
};
export const trimDependantChangePaths = (
changePaths: Set<string>,
dependencyMap: DependencyMap,
): Array<string> => {
const trimmedPaths = [];
for (const path of changePaths) {
let foundADependant = false;
if (path in dependencyMap) {
const dependants = dependencyMap[path];
for (const dependantPath of dependants) {
if (changePaths.has(dependantPath)) {
foundADependant = true;
break;
}
}
}
if (!foundADependant) {
trimmedPaths.push(path);
}
}
return trimmedPaths;
};
2021-02-22 11:14:08 +00:00
export function getSafeToRenderDataTree(
tree: DataTree,
widgetTypeConfigMap: WidgetTypeConfigMap,
) {
return Object.keys(tree).reduce((tree, entityKey: string) => {
const entity = tree[entityKey] as DataTreeWidget;
if (!isWidget(entity)) {
return tree;
}
const safeToRenderEntity = { ...entity };
// Set user input values to their parsed values
Object.entries(entity.validationPaths).forEach(([property, validation]) => {
const value = _.get(entity, property);
// Pass it through parse
feat: JSON Form widget (#8472) * initial layout * updated parser to support nested array * array field rendering * changes * ts fix * minor revert FormWidget * modified schema structure * select and switch fields * added checkbox field * added RadioGroupField * partial DateField and defaults, typing refactoring * added label and field type change * minor ts changes * changes * modified widget/utils for nested panelConfig, modified schema to object approach * array/object label support * hide field configuration when children not present * added tooltip * field visibility option * disabled state * upgraded tslib, form initial values * custom field configuration - add/hide/edit * field configuration - label change * return input when field configuration reaches max depth * minor changes * form - scroll, fixedfooter, enitity defn and other minior changes * form title * unregister on unmount * fixes * zero state * fix field padding * patched updating form values, removed linting warnings * configured action buttons * minor fix * minor change * property pane - sort fields in field configuration * refactor include all properties * checkbox properties * date properties * refactor typings and radio group properties * switch, multselect, select, array, object properties * minor changes * default value * ts fixes * checkbox field properties implementation * date field prop implementation * switch field * select field and fix deep nested meta properties * multiselect implementation * minor change * input field implementation * fix position jump on field type change * initial accordian * field state property and auto-complete of JSONFormComputeControl * merge fixes * renamed FormBuilder to JSONForm * source data validation minor change * custom field default value fix * Editable keys for custom field * minor fixes * replaced useFieldArray with custom logic, added widget icon * array and object accordian with border/background styling * minor change * disabled states for array and objects * default value minor fix * form level styles * modified logic for isDisabled for array and object, added disabledWhenInvalid, exposed isValid to fieldState for text input, removed useDisableChildren * added isValid for all field types * fixed reset to default values * debounce form values update * minor change * minor change * fix crash - source data change multi-select to array, fix crash - change of options * fix positioning * detect date type in source data * fix crash - when object is passed to regex input field * fixed default sourceData path for fields * accodion keep children mounted on collapse * jest test for schemaParser * widget/helper and useRegisterFieldInvalid test * tests for property config helper and generatePanelPropertyConfig * fix input field validation not appearing * fix date field type detection * rename data -> formData * handle null/undefined field value change in sourceData * added null/undefined as valid values for defaultValue text field * auto detect email field * set formData default value on initial load * switch field inline positioning * field margin fix for row direction * select full width * fiex date field default value - out of range * fix any field type to array * array default value logic change * base cypress test changes * initial json form render cy test * key sanitization * fix fieldState update logic * required design, object/array background color, accordion changes, fix - add new custom field * minor change * cypress tests * fix date formatted value, field state cypress test * cypress - field properties test and fixes * rename test file * fix accessort change to blank value, cypress tests * fix array field default value for modified accessor * minor fix * added animate loading * fix empty state, add new custom field * test data fix * fix warnings * fix timePrecision visibility * button styling * ported input v2 * fix jest tests * fix cypress tests * perf changes * perf improvement * added comments * multiselect changes * input field perf refactor * array field, object field refactor performance * checkbox field refactor * refectored date, radio, select and switch * fixes * test fixes * fixes * minor fix * rename field renderer * remove tracked fieldRenderer field * cypress test fixes * cypress changes * array default value fixes * arrayfield passedDefaultValue * auto enabled JS mode for few properties, reverted swith and date property controls * cypress changes * added widget sniping mode and fixed object passedDefaultValue * multiselect v2 * select v2 * fix jest tests * test fixes * field limit * rename field type dropdown texts * field type changes fixes * jest fixes * loading state submit button * default source data for new widget * modify limit message * multiseelct default value changes and cypress fix * select default value * keep default value intact on field type change * TextTable cypress text fix * review changes * fixed footer changes * collapse styles section by default * fixed footer changes * form modes * custom field key rentention * fixed footer fix in view mode * non ascii characters * fix meta merge in dataTreeWidget * minor fixes * rename useRegisterFieldInvalid.ts -> useRegisterFieldValidity.ts * modified dependency injection into evaluated values * refactored fixedfooter logic * minor change * accessor update * minor change * fixes * QA fixes date field, scroll content * fix phone number field, removed visiblity option from array item * fix sourceData autocomplete * reset logic * fix multiselect reset * form values hydration on widget drag * code review changes * reverted order of merge dataTreeWidget * fixes * added button titles, fixed hydration issue * default value fixes * upgraded react hook form, modified array-level/field-level default value logic * fixed select validation * added icon entity explorer, modified icon align control * modify accessor validation for mongo db _id * update email field regex * review changes * explicitly handle empty source data validation
2022-03-24 07:13:25 +00:00
const { parsed } = validateWidgetProperty(
validation,
value,
entity,
property,
);
_.set(safeToRenderEntity, property, parsed);
});
// Set derived values to undefined or else they would go as bindings
Object.keys(widgetTypeConfigMap[entity.type].derivedProperties).forEach(
(property) => {
_.set(safeToRenderEntity, property, undefined);
},
);
return { ...tree, [entityKey]: safeToRenderEntity };
}, tree);
}
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
export const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;
export const ARGUMENT_NAMES = /([^\s,]+)/g;
export function getParams(func: any) {
const fnStr = func.toString().replace(STRIP_COMMENTS, "");
const args: Array<Variable> = [];
let result = fnStr
.slice(fnStr.indexOf("(") + 1, fnStr.indexOf(")"))
.match(ARGUMENT_NAMES);
if (result === null) result = [];
if (result && result.length) {
result.forEach((arg: string) => {
const element = arg.split("=");
args.push({
name: element[0],
value: element[1],
});
});
}
return args;
}
export const addErrorToEntityProperty = (
errors: EvaluationError[],
dataTree: DataTree,
path: string,
) => {
const { entityName, propertyPath } = getEntityNameAndPropertyPath(path);
const isPrivateEntityPath = getAllPrivateWidgetsInDataTree(dataTree)[
entityName
];
const logBlackList = _.get(dataTree, `${entityName}.logBlackList`, {});
if (propertyPath && !(propertyPath in logBlackList) && !isPrivateEntityPath) {
const existingErrors = _.get(
dataTree,
`${entityName}.${EVAL_ERROR_PATH}['${propertyPath}']`,
[],
) as EvaluationError[];
_.set(
dataTree,
`${entityName}.${EVAL_ERROR_PATH}['${propertyPath}']`,
existingErrors.concat(errors),
);
}
return dataTree;
};
// For the times when you need to know if something truly an object like { a: 1, b: 2}
// typeof, lodash.isObject and others will return false positives for things like array, null, etc
2021-07-20 10:02:56 +00:00
export const isTrueObject = (
item: unknown,
): item is Record<string, unknown> => {
return Object.prototype.toString.call(item) === "[object Object]";
};
export const isDynamicLeaf = (unEvalTree: DataTree, propertyPath: string) => {
const [entityName, ...propPathEls] = _.toPath(propertyPath);
// Framework feature: Top level items are never leaves
if (entityName === propertyPath) return false;
// Ignore if this was a delete op
if (!(entityName in unEvalTree)) return false;
const entity = unEvalTree[entityName];
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
if (!isAction(entity) && !isWidget(entity) && !isJSAction(entity))
return false;
const relativePropertyPath = convertPathToString(propPathEls);
return (
relativePropertyPath in entity.bindingPaths ||
(isWidget(entity) && relativePropertyPath in entity.triggerPaths)
);
};
export const updateJSCollectionInDataTree = (
parsedBody: ParsedBody,
jsCollection: DataTreeJSAction,
dataTree: DataTree,
) => {
const modifiedDataTree: any = dataTree;
const functionsList: Array<string> = [];
const varList: Array<string> = jsCollection.variables;
Object.keys(jsCollection.meta).forEach((action) => {
functionsList.push(action);
});
if (parsedBody.actions && parsedBody.actions.length > 0) {
for (let i = 0; i < parsedBody.actions.length; i++) {
const action = parsedBody.actions[i];
if (jsCollection.hasOwnProperty(action.name)) {
if (jsCollection[action.name] !== action.body) {
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
const data = _.get(
modifiedDataTree,
`${jsCollection.name}.${action.name}.data`,
{},
);
_.set(
modifiedDataTree,
`${jsCollection.name}.${action.name}`,
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
new String(action.body),
);
_.set(
modifiedDataTree,
`${jsCollection.name}.${action.name}.data`,
data,
);
}
} else {
const bindingPaths = jsCollection.bindingPaths;
bindingPaths[action.name] = EvaluationSubstitutionType.SMART_SUBSTITUTE;
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
bindingPaths[`${action.name}.data`] =
EvaluationSubstitutionType.TEMPLATE;
_.set(
modifiedDataTree,
`${jsCollection.name}.bindingPaths`,
bindingPaths,
);
const dynamicBindingPathList = jsCollection.dynamicBindingPathList;
dynamicBindingPathList.push({ key: action.name });
_.set(
modifiedDataTree,
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
`${jsCollection.name}.dynamicBindingPathList`,
dynamicBindingPathList,
);
const dependencyMap = jsCollection.dependencyMap;
dependencyMap["body"].push(action.name);
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
_.set(
modifiedDataTree,
`${jsCollection.name}.dependencyMap`,
dependencyMap,
);
const meta = jsCollection.meta;
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
meta[action.name] = {
arguments: action.arguments,
isAsync: false,
confirmBeforeExecute: false,
};
_.set(modifiedDataTree, `${jsCollection.name}.meta`, meta);
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
const data = _.get(
modifiedDataTree,
`${jsCollection.name}.${action.name}.data`,
{},
);
_.set(
modifiedDataTree,
`${jsCollection.name}.${action.name}`,
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
new String(action.body.toString()),
);
_.set(
modifiedDataTree,
`${jsCollection.name}.${action.name}.data`,
data,
);
}
}
}
if (functionsList && functionsList.length > 0) {
for (let i = 0; i < functionsList.length; i++) {
const preAction = functionsList[i];
const existed = parsedBody.actions.find(
(js: ParsedJSSubAction) => js.name === preAction,
);
if (!existed) {
const bindingPaths = jsCollection.bindingPaths;
delete bindingPaths[preAction];
_.set(
modifiedDataTree,
`${jsCollection.name}.bindingPaths`,
bindingPaths,
);
let dynamicBindingPathList = jsCollection.dynamicBindingPathList;
dynamicBindingPathList = dynamicBindingPathList.filter(
(path) => path["key"] !== preAction,
);
_.set(
modifiedDataTree,
`${jsCollection.name}.dynamicBindingPathList`,
dynamicBindingPathList,
);
const dependencyMap = jsCollection.dependencyMap["body"];
const removeIndex = dependencyMap.indexOf(preAction);
if (removeIndex > -1) {
const updatedDMap = dependencyMap.filter(
(item) => item !== preAction,
);
_.set(
modifiedDataTree,
`${jsCollection.name}.dependencyMap.body`,
updatedDMap,
);
}
const meta = jsCollection.meta;
delete meta[preAction];
_.set(modifiedDataTree, `${jsCollection.name}.meta`, meta);
delete modifiedDataTree[`${jsCollection.name}`][`${preAction}`];
feat: Settings js editor (#9984) * POC * Closing channels * WIP * v1 * get working with JS editor * autocomplete * added comments * try removing an import * different way of import * dependency map added to body * triggers can be part of js editor functions hence * removed unwanted lines * new flow chnages * Resolve conflicts * small css changes for empty state * Fix prettier * Fixes * flow changes part 2 * Mock web worker for testing * Throw errors during evaluation * Action execution should be non blocking on the main thread to evaluation of further actions * WIP * Fix build issue * Fix warnings * Rename * Refactor and add tests for worker util * Fix response flow post refactor * added settings icon for js editor * WIP * WIP * WIP * Tests for promises * settings for each function of js object added * Error handling * Error handing action validation * Update test * Passing callback data in the eval trigger flow * log triggers to be executed * WIP * confirm before execution * Remove debugging * Fix backwards compatibility * Avoid passing trigger meta around * fix button loading * handle error callbacks * fix tests * tests * fix console error when checking for async * Fix async function check * Fix async function check again * fix bad commit * Add some comments * added clientSideExecution flag for js functions * css changes for settings icon * unsued code removed * on page load PART 1 * onPageLoad rest iof changes * corrected async badge * removed duplicate test cases * added confirm modal for js functions * removed unused code * small chnage * dependency was not getting created * Fix confirmation modal * unused code removed * replaced new confirmsaga * confirmaton box changes * Fixing JSEditor Run butn locator * corrected property * dependency map was failing * changed key for confirmation box Co-authored-by: hetunandu <hetu@appsmith.com> Co-authored-by: Hetu Nandu <hetunandu@gmail.com> Co-authored-by: Arpit Mohan <arpit@appsmith.com> Co-authored-by: Aishwarya UR <aishwarya@appsmith.com>
2022-03-17 12:05:17 +00:00
delete modifiedDataTree[`${jsCollection.name}`][`${preAction}.data`];
}
}
}
if (parsedBody.variables.length) {
for (let i = 0; i < parsedBody.variables.length; i++) {
const newVar = parsedBody.variables[i];
const existedVar = varList.indexOf(newVar.name);
if (existedVar > -1) {
const existedVarVal = jsCollection[newVar.name];
if (
(!!existedVarVal && existedVarVal.toString()) !==
(newVar.value && newVar.value.toString()) ||
(!existedVarVal && !!newVar)
) {
_.set(
modifiedDataTree,
`${jsCollection.name}.${newVar.name}`,
newVar.value,
);
}
} else {
varList.push(newVar.name);
_.set(modifiedDataTree, `${jsCollection.name}.variables`, varList);
_.set(
modifiedDataTree,
`${jsCollection.name}.${newVar.name}`,
newVar.value,
);
}
}
let newVarList: Array<string> = [];
for (let i = 0; i < varList.length; i++) {
const varListItem = varList[i];
const existsInParsed = parsedBody.variables.find(
(item) => item.name === varListItem,
);
if (!existsInParsed) {
delete modifiedDataTree[`${jsCollection.name}`][`${varListItem}`];
newVarList = varList.filter((item) => item !== varListItem);
}
}
if (newVarList.length) {
_.set(modifiedDataTree, `${jsCollection.name}.variables`, newVarList);
}
}
return modifiedDataTree;
};
export const removeFunctionsAndVariableJSCollection = (
dataTree: DataTree,
entity: DataTreeJSAction,
) => {
const modifiedDataTree: any = dataTree;
const functionsList: Array<string> = [];
Object.keys(entity.meta).forEach((action) => {
functionsList.push(action);
});
//removed variables
const varList: Array<string> = entity.variables;
_.set(modifiedDataTree, `${entity.name}.variables`, []);
for (let i = 0; i < varList.length; i++) {
const varName = varList[i];
delete modifiedDataTree[`${entity.name}`][`${varName}`];
}
//remove functions
let dynamicBindingPathList = entity.dynamicBindingPathList;
const bindingPaths = entity.bindingPaths;
const meta = entity.meta;
let dependencyMap = entity.dependencyMap["body"];
for (let i = 0; i < functionsList.length; i++) {
const actionName = functionsList[i];
delete bindingPaths[actionName];
delete meta[actionName];
delete modifiedDataTree[`${entity.name}`][`${actionName}`];
dynamicBindingPathList = dynamicBindingPathList.filter(
(path: any) => path["key"] !== actionName,
);
dependencyMap = dependencyMap.filter((item: any) => item !== actionName);
}
_.set(modifiedDataTree, `${entity.name}.bindingPaths`, bindingPaths);
_.set(
modifiedDataTree,
`${entity.name}.dynamicBindingPathList`,
dynamicBindingPathList,
);
_.set(modifiedDataTree, `${entity.name}.dependencyMap.body`, dependencyMap);
_.set(modifiedDataTree, `${entity.name}.meta`, meta);
return modifiedDataTree;
};
export const addWidgetPropertyDependencies = ({
entity,
entityName,
}: {
entity: DataTreeWidget;
entityName: string;
}) => {
const dependencies: DependencyMap = {};
Object.entries(entity.propertyOverrideDependency).forEach(
([overriddenPropertyKey, overridingPropertyKeyMap]) => {
const existingDependenciesSet = new Set(
dependencies[`${entityName}.${overriddenPropertyKey}`] || [],
);
// add meta dependency
overridingPropertyKeyMap.META &&
existingDependenciesSet.add(
`${entityName}.${overridingPropertyKeyMap.META}`,
);
// add default dependency
overridingPropertyKeyMap.DEFAULT &&
existingDependenciesSet.add(
`${entityName}.${overridingPropertyKeyMap.DEFAULT}`,
);
dependencies[`${entityName}.${overriddenPropertyKey}`] = [
...existingDependenciesSet,
];
},
);
return dependencies;
};
export const isPrivateEntityPath = (
privateWidgets: PrivateWidgets,
fullPropertyPath: string,
) => {
const entityName = fullPropertyPath.split(".")[0];
if (Object.keys(privateWidgets).indexOf(entityName) !== -1) {
return true;
}
return false;
};
export const getAllPrivateWidgetsInDataTree = (
dataTree: DataTree,
): PrivateWidgets => {
let privateWidgets: PrivateWidgets = {};
Object.keys(dataTree).forEach((entityName) => {
const entity = dataTree[entityName];
if (isWidget(entity) && !_.isEmpty(entity.privateWidgets)) {
privateWidgets = { ...privateWidgets, ...entity.privateWidgets };
}
});
return privateWidgets;
};
export const getDataTreeWithoutPrivateWidgets = (
dataTree: DataTree,
): DataTree => {
const privateWidgets = getAllPrivateWidgetsInDataTree(dataTree);
const privateWidgetNames = Object.keys(privateWidgets);
const treeWithoutPrivateWidgets = _.omit(dataTree, privateWidgetNames);
return treeWithoutPrivateWidgets;
};
export const overrideWidgetProperties = (
entity: DataTreeWidget,
propertyPath: string,
value: unknown,
currentTree: DataTree,
) => {
const clonedValue = clone(value);
if (propertyPath in entity.overridingPropertyPaths) {
const overridingPropertyPaths =
entity.overridingPropertyPaths[propertyPath];
overridingPropertyPaths.forEach((overriddenPropertyPath) => {
const overriddenPropertyPathArray = overriddenPropertyPath.split(".");
_.set(
currentTree,
[entity.widgetName, ...overriddenPropertyPathArray],
clonedValue,
);
});
} else if (
propertyPath in entity.propertyOverrideDependency &&
clonedValue === undefined
) {
// when value is undefined and has default value then set value to default value.
// this is for resetForm
const propertyOverridingKeyMap =
entity.propertyOverrideDependency[propertyPath];
if (propertyOverridingKeyMap.DEFAULT) {
const defaultValue = entity[propertyOverridingKeyMap.DEFAULT];
const clonedDefaultValue = clone(defaultValue);
if (defaultValue !== undefined) {
const propertyPathArray = propertyPath.split(".");
_.set(
currentTree,
[entity.widgetName, ...propertyPathArray],
clonedDefaultValue,
);
return {
overwriteParsedValue: true,
newValue: clonedDefaultValue,
};
}
}
}
};