level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
1,427
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils/autocomplete
petrpan-code/appsmithorg/appsmith/app/client/src/utils/autocomplete/__tests__/AutocompleteSortRules.test.ts
import type { FieldEntityInformation } from "components/editorComponents/CodeEditor/EditorConfig"; import { AutocompleteSorter } from "../AutocompleteSortRules"; import type { Completion, DataTreeDefEntityInformation, TernCompletionResult, } from "../CodemirrorTernService"; import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory"; describe("Autocomplete Ranking", () => { it("Blocks platform functions in data fields", () => { const completions: unknown[] = [ { text: "appsmith", displayText: "appsmith", className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-object", data: { name: "appsmith", type: "appsmith", origin: "DATA_TREE", }, origin: "DATA_TREE", type: "OBJECT", isHeader: false, }, { text: "atob()", displayText: "atob()", className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", data: { name: "atob", type: "fn(bString: string) -> string", doc: "decodes a base64 encoded string", origin: "base64-js", }, origin: "base64-js", type: "FUNCTION", isHeader: false, }, { text: "APIQuery", displayText: "APIQuery", className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-object", data: { name: "APIQuery", type: "APIQuery", doc: "Actions allow you to connect your widgets to your backend data in a secure manner.", url: "https://docs.appsmith.com/reference/appsmith-framework/query-object", origin: "DATA_TREE", }, origin: "DATA_TREE", type: "OBJECT", isHeader: false, }, { text: "APIQuery.clear()", displayText: "APIQuery.clear()", className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", data: { name: "APIQuery.clear", type: "fn()", origin: "DATA_TREE", }, origin: "DATA_TREE", type: "FUNCTION", isHeader: false, }, { text: "APIQuery.data", displayText: "APIQuery.data", className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-unknown", data: { name: "APIQuery.data", type: "?", doc: "The response of the action", origin: "DATA_TREE", }, origin: "DATA_TREE", type: "UNKNOWN", isHeader: false, }, { text: "APIQuery.run()", displayText: "APIQuery.run()", className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", data: { name: "APIQuery.run", type: "fn(params: ?)", origin: "DATA_TREE", }, origin: "DATA_TREE", type: "FUNCTION", isHeader: false, }, { text: "Array()", displayText: "Array()", className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", data: { name: "Array", type: "fn(size: number)", doc: "The JavaScript Array global object is a constructor for arrays, which are high-level, list-like objects.", url: "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array", origin: "ecmascript", }, origin: "ecmascript", type: "FUNCTION", isHeader: false, }, { text: "showAlert()", displayText: "showAlert()", className: "CodeMirror-Tern-completion CodeMirror-Tern-completion-fn", data: { name: "showAlert", type: "fn(message: string, style: string)", doc: "Show a temporary notification style message to the user", origin: "DATA_TREE.APPSMITH.FUNCTIONS", }, origin: "DATA_TREE.APPSMITH.FUNCTIONS", type: "FUNCTION", isHeader: false, }, ]; const currentFieldInfo: unknown = { expectedType: "ARRAY", example: '[{ "name": "John" }]', mode: "text-js", entityName: "Table1", entityType: "WIDGET", entityId: "xy1ezsr0l5", widgetType: "TABLE_WIDGET_V2", propertyPath: "tableData", token: { start: 2, end: 3, string: "A", type: "variable", state: { outer: true, innerActive: { open: "{{", close: "}}", delimStyle: "binding-brackets", mode: { electricInput: {}, blockCommentStart: null, blockCommentEnd: null, blockCommentContinue: null, lineComment: null, fold: "brace", closeBrackets: "()[]{}''\"\"``", helperType: "json", jsonMode: true, name: "javascript", }, }, inner: { lastType: "variable", cc: [null], lexical: { indented: -2, column: 0, type: "block", align: false, }, indented: 0, }, startingInner: false, }, }, }; const entityInfo: DataTreeDefEntityInformation = { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET_V2", }; const sortedCompletionsText = AutocompleteSorter.sort( completions as Completion<TernCompletionResult>[], currentFieldInfo as FieldEntityInformation, entityInfo, true, ).map((c) => c.displayText); expect(sortedCompletionsText).not.toEqual( expect.arrayContaining(["showAlert(), APIQuery.clear(), APIQuery.run()"]), ); }); });
1,428
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils/autocomplete
petrpan-code/appsmithorg/appsmith/app/client/src/utils/autocomplete/__tests__/TernServer.test.ts
import type { Completion, DataTreeDefEntityInformation, } from "../CodemirrorTernService"; import CodemirrorTernService, { createCompletionHeader, } from "../CodemirrorTernService"; import { AutocompleteDataType } from "../AutocompleteDataType"; import { MockCodemirrorEditor } from "../../../../test/__mocks__/CodeMirrorEditorMock"; import { ENTITY_TYPE_VALUE } from "entities/DataTree/dataTreeFactory"; import _ from "lodash"; import { AutocompleteSorter, ScoredCompletion } from "../AutocompleteSortRules"; import type CodeMirror from "codemirror"; jest.mock("utils/getCodeMirrorNamespace", () => { const actual = jest.requireActual("utils/getCodeMirrorNamespace"); return { ...actual, getCodeMirrorNamespaceFromDoc: jest.fn((doc) => ({ ...actual.getCodeMirrorNamespaceFromDoc(doc), innerMode: jest.fn(() => ({ mode: { name: "", }, state: { lexical: {}, }, })), })), }; }); describe("Tern server", () => { it("Check whether the correct value is being sent to tern", () => { const testCases = [ { input: { name: "test", doc: { getCursor: () => ({ ch: 0, line: 0 }), getLine: () => "{{Api.}}", getValue: () => "{{Api.}}", } as unknown as CodeMirror.Doc, changed: null, }, expectedOutput: "{{Api.}}", }, { input: { name: "test", doc: { getCursor: () => ({ ch: 0, line: 0 }), getLine: () => "a{{Api.}}", getValue: () => "a{{Api.}}", } as unknown as CodeMirror.Doc, changed: null, }, expectedOutput: "a{{Api.}}", }, { input: { name: "test", doc: { getCursor: () => ({ ch: 10, line: 0 }), getLine: () => "a{{Api.}}bc", getValue: () => "a{{Api.}}bc", } as unknown as CodeMirror.Doc, changed: null, }, expectedOutput: "a{{Api.}}bc", }, { input: { name: "test", doc: { getCursor: () => ({ ch: 4, line: 0 }), getLine: () => "a{{Api.}}", getValue: () => "a{{Api.}}", } as unknown as CodeMirror.Doc, changed: null, }, expectedOutput: "Api.", }, ]; testCases.forEach((testCase) => { const { value } = CodemirrorTernService.getFocusedDocValueAndPos( testCase.input, ); expect(value).toBe(testCase.expectedOutput); }); }); it("Check whether the correct position is sent for querying autocomplete", () => { const testCases = [ { input: { name: "test", doc: { getCursor: () => ({ ch: 0, line: 0 }), getLine: () => "{{Api.}}", somethingSelected: () => false, getValue: () => "{{Api.}}", } as unknown as CodeMirror.Doc, changed: null, }, expectedOutput: { ch: 0, line: 0 }, }, { input: { name: "test", doc: { getCursor: () => ({ ch: 0, line: 0 }), getLine: () => "{{Api.}}", somethingSelected: () => false, getValue: () => "{{Api.}}", } as unknown as CodeMirror.Doc, changed: null, }, expectedOutput: { ch: 0, line: 0 }, }, { input: { name: "test", doc: { getCursor: () => ({ ch: 8, line: 0 }), getLine: () => "g {{Api.}}", somethingSelected: () => false, getValue: () => "g {{Api.}}", } as unknown as CodeMirror.Doc, changed: null, }, expectedOutput: { ch: 4, line: 0 }, }, { input: { name: "test", doc: { getCursor: () => ({ ch: 7, line: 1 }), getLine: () => "c{{Api.}}", somethingSelected: () => false, getValue: () => "ab\nc{{Api.}}", } as unknown as CodeMirror.Doc, changed: null, }, expectedOutput: { ch: 4, line: 0 }, }, ]; testCases.forEach((testCase) => { MockCodemirrorEditor.getTokenAt.mockReturnValueOnce({ type: "string", string: "", }); const request = CodemirrorTernService.buildRequest(testCase.input, {}); expect(request.query.end).toEqual(testCase.expectedOutput); }); }); it(`Check whether the position is evaluated correctly for placing the selected autocomplete value`, () => { const testCases = [ { input: { codeEditor: { value: "{{}}", cursor: { ch: 2, line: 0 }, doc: { getCursor: () => ({ ch: 2, line: 0 }), getLine: () => "{{}}", somethingSelected: () => false, getValue: () => "{{}}", getEditor: () => MockCodemirrorEditor, } as unknown as CodeMirror.Doc, }, requestCallbackData: { completions: [{ name: "Api1" }], start: { ch: 2, line: 0 }, end: { ch: 6, line: 0 }, }, }, expectedOutput: { ch: 2, line: 0 }, }, { input: { codeEditor: { value: "\n {{}}", cursor: { ch: 3, line: 0 }, doc: { getCursor: () => ({ ch: 3, line: 0 }), getLine: () => " {{}}", somethingSelected: () => false, getValue: () => " {{}}", getEditor: () => MockCodemirrorEditor, } as unknown as CodeMirror.Doc, }, requestCallbackData: { completions: [{ name: "Api1" }], start: { ch: 0, line: 0 }, end: { ch: 4, line: 0 }, }, }, expectedOutput: { ch: 3, line: 0 }, }, ]; testCases.forEach((testCase) => { MockCodemirrorEditor.getValue.mockReturnValueOnce( testCase.input.codeEditor.value, ); MockCodemirrorEditor.getCursor.mockReturnValueOnce( testCase.input.codeEditor.cursor, ); MockCodemirrorEditor.getDoc.mockReturnValue( testCase.input.codeEditor.doc, ); MockCodemirrorEditor.getTokenAt.mockReturnValueOnce({ type: "string", string: "", }); const mockAddFile = jest.fn(); CodemirrorTernService.server.addFile = mockAddFile; const value: any = CodemirrorTernService.requestCallback( null, testCase.input.requestCallbackData as any, MockCodemirrorEditor as unknown as CodeMirror.Editor, () => null, ); expect(mockAddFile).toBeCalled(); expect(value.from).toEqual(testCase.expectedOutput); }); }); }); describe("Tern server sorting", () => { const defEntityInformation: Map<string, DataTreeDefEntityInformation> = new Map(); const contextCompletion: Completion = { text: "context", type: AutocompleteDataType.STRING, origin: "[doc]", data: { doc: "", }, }; const sameEntityCompletion: Completion<any> = { text: "sameEntity.tableData", type: AutocompleteDataType.ARRAY, origin: "DATA_TREE", data: {}, }; defEntityInformation.set("sameEntity", { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET", }); defEntityInformation.set("sameEntity", { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET_V2", }); const priorityCompletion: Completion<any> = { text: "selectedRow", type: AutocompleteDataType.OBJECT, origin: "DATA_TREE", data: {}, }; defEntityInformation.set("sameType", { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET", }); defEntityInformation.set("sameType", { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET_V2", }); const diffTypeCompletion: Completion<any> = { text: "diffType.tableData", type: AutocompleteDataType.ARRAY, origin: "DATA_TREE.WIDGET", data: {}, }; defEntityInformation.set("diffType", { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET", }); defEntityInformation.set("diffType", { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET_V2", }); const sameTypeDiffEntityTypeCompletion: Completion<any> = { text: "diffEntity.data", type: AutocompleteDataType.OBJECT, origin: "DATA_TREE", data: {}, }; defEntityInformation.set("diffEntity", { type: ENTITY_TYPE_VALUE.ACTION, subType: ENTITY_TYPE_VALUE.ACTION, }); const dataTreeCompletion: Completion<any> = { text: "otherDataTree", type: AutocompleteDataType.STRING, origin: "DATA_TREE", data: {}, }; defEntityInformation.set("otherDataTree", { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TEXT_WIDGET", }); const functionCompletion: Completion<any> = { text: "otherDataFunction", type: AutocompleteDataType.FUNCTION, origin: "DATA_TREE.APPSMITH.FUNCTIONS", data: {}, }; const ecmascriptCompletion: Completion<any> = { text: "otherJS", type: AutocompleteDataType.OBJECT, origin: "ecmascript", data: {}, }; const libCompletion: Completion<any> = { text: "libValue", type: AutocompleteDataType.OBJECT, origin: "LIB/lodash", data: {}, }; const unknownCompletion: Completion<any> = { text: "unknownSuggestion", type: AutocompleteDataType.UNKNOWN, origin: "unknown", data: {}, }; const completions = [ sameEntityCompletion, priorityCompletion, contextCompletion, libCompletion, unknownCompletion, diffTypeCompletion, sameTypeDiffEntityTypeCompletion, ecmascriptCompletion, functionCompletion, dataTreeCompletion, ]; it("shows best match results", () => { CodemirrorTernService.setEntityInformation( MockCodemirrorEditor as unknown as CodeMirror.Editor, { entityName: "sameEntity", entityType: ENTITY_TYPE_VALUE.WIDGET, expectedType: AutocompleteDataType.OBJECT, }, ); CodemirrorTernService.defEntityInformation = defEntityInformation; const sortedCompletions = AutocompleteSorter.sort( _.shuffle(completions), { entityName: "sameEntity", entityType: ENTITY_TYPE_VALUE.WIDGET, expectedType: AutocompleteDataType.STRING, }, { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET", }, ); expect(sortedCompletions[1]).toStrictEqual(contextCompletion); expect(sortedCompletions).toEqual( expect.arrayContaining([ createCompletionHeader("Best match"), sameTypeDiffEntityTypeCompletion, createCompletionHeader("Search results"), dataTreeCompletion, ]), ); }); it("tests score of completions", function () { AutocompleteSorter.entityDefInfo = { type: ENTITY_TYPE_VALUE.WIDGET, subType: "TABLE_WIDGET", }; AutocompleteSorter.currentFieldInfo = { entityName: "sameEntity", entityType: ENTITY_TYPE_VALUE.WIDGET, expectedType: AutocompleteDataType.STRING, }; //completion that matches type and is present in dataTree. const scoredCompletion1 = new ScoredCompletion( dataTreeCompletion, AutocompleteSorter.currentFieldInfo, ); expect(scoredCompletion1.score).toEqual(2 ** 6 + 2 ** 4 + 2 ** 3); //completion that belongs to the same entity. const scoredCompletion2 = new ScoredCompletion( sameEntityCompletion, AutocompleteSorter.currentFieldInfo, ); expect(scoredCompletion2.score).toEqual(-Infinity); //completion that is a priority. const scoredCompletion3 = new ScoredCompletion( priorityCompletion, AutocompleteSorter.currentFieldInfo, ); expect(scoredCompletion3.score).toBe(2 ** 8 + 2 ** 4 + 2 ** 3); }); });
1,429
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils/autocomplete
petrpan-code/appsmithorg/appsmith/app/client/src/utils/autocomplete/__tests__/dataTreeTypeDefCreator.test.ts
import { dataTreeTypeDefCreator } from "utils/autocomplete/dataTreeTypeDefCreator"; import type { WidgetEntity, WidgetEntityConfig, } from "@appsmith/entities/DataTree/types"; import { ENTITY_TYPE_VALUE, EvaluationSubstitutionType, } from "entities/DataTree/dataTreeFactory"; import InputWidget from "widgets/InputWidgetV2"; import { registerWidgets } from "WidgetProvider/factory/registrationHelper"; import { flattenDef, generateTypeDef, getFunctionsArgsType, } from "../defCreatorUtils"; describe("dataTreeTypeDefCreator", () => { it("creates the right def for a widget", () => { registerWidgets([InputWidget]); const dataTreeEntity: WidgetEntity = { widgetId: "yolo", widgetName: "Input1", parentId: "123", renderMode: "CANVAS", text: "yo", type: "INPUT_WIDGET_V2", ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET, parentColumnSpace: 1, parentRowSpace: 2, leftColumn: 2, rightColumn: 3, topRow: 1, bottomRow: 2, isLoading: false, version: 1, meta: {}, }; const dataTreeEntityConfig: WidgetEntityConfig = { bindingPaths: { defaultText: EvaluationSubstitutionType.TEMPLATE, }, reactivePaths: { defaultText: EvaluationSubstitutionType.TEMPLATE, }, triggerPaths: { onTextChange: true, }, validationPaths: {}, logBlackList: {}, propertyOverrideDependency: {}, overridingPropertyPaths: {}, privateWidgets: {}, defaultMetaProps: [], widgetId: "yolo", widgetName: "Input1", type: "INPUT_WIDGET_V2", ENTITY_TYPE: ENTITY_TYPE_VALUE.WIDGET, }; const { def, entityInfo } = dataTreeTypeDefCreator( { Input1: dataTreeEntity, }, {}, dataTreeEntityConfig, ); // TODO hetu: needs better general testing // instead of testing each widget maybe we can test to ensure // that defs are in a correct format expect(def.Input1).toStrictEqual(InputWidget.getAutocompleteDefinitions()); expect(def).toHaveProperty("Input1.isDisabled"); expect(entityInfo.get("Input1")).toStrictEqual({ type: ENTITY_TYPE_VALUE.WIDGET, subType: "INPUT_WIDGET_V2", }); }); it("creates a correct def for an object", () => { const obj = { yo: "lo", someNumber: 12, someString: "123", someBool: false, unknownProp: undefined, nested: { someExtraNested: "yolo", }, }; const expected = { yo: "string", someNumber: "number", someString: "string", someBool: "bool", unknownProp: "?", nested: { someExtraNested: "string", }, }; const objType = generateTypeDef(obj); expect(objType).toStrictEqual(expected); }); it("creates a correct def for a complex array of object", () => { const data = [ { nested: [ { nested: [ { nested: [ { nested: [ { nested: [ { nested: [ { name: "", email: "", }, ], }, ], }, ], }, ], }, ], }, ], }, ]; const expected = "[def_6]"; const extraDef = {}; const expectedExtraDef = { def_1: { nested: "[?]" }, def_2: { nested: "[def_1]" }, def_3: { nested: "[def_2]" }, def_4: { nested: "[def_3]" }, def_5: { nested: "[def_4]" }, def_6: { nested: "[def_5]" }, }; const dataType = generateTypeDef(data, extraDef); expect(dataType).toStrictEqual(expected); expect(extraDef).toStrictEqual(expectedExtraDef); const extraDef2 = {}; const expected2 = "[def_10]"; const dataType2 = generateTypeDef( data[0].nested[0].nested[0].nested, extraDef2, ); const expectedExtraDef2 = { def_7: { name: "string", email: "string" }, def_8: { nested: "[def_7]" }, def_9: { nested: "[def_8]" }, def_10: { nested: "[def_9]" }, }; expect(dataType2).toStrictEqual(expected2); expect(extraDef2).toStrictEqual(expectedExtraDef2); }); it("creates a correct def for an array of array of object", () => { const array = [[{ name: "", email: "" }]]; const expected = "[[def_11]]"; const extraDefsToDefine = {}; const expectedExtraDef = { def_11: { name: "string", email: "string" }, }; const objType = generateTypeDef(array, extraDefsToDefine); expect(objType).toStrictEqual(expected); expect(extraDefsToDefine).toStrictEqual(expectedExtraDef); }); it("flatten def", () => { const def = { entity1: { someNumber: "number", someString: "string", someBool: "bool", nested: { someExtraNested: "string", }, }, }; const expected = { entity1: { someNumber: "number", someString: "string", someBool: "bool", nested: { someExtraNested: "string", }, }, "entity1.someNumber": "number", "entity1.someString": "string", "entity1.someBool": "bool", "entity1.nested": { someExtraNested: "string", }, "entity1.nested.someExtraNested": "string", }; const value = flattenDef(def, "entity1"); expect(value).toStrictEqual(expected); }); }); describe("getFunctionsArgsType", () => { const testCases = { testCase1: { arguments: [ { name: "a", value: undefined }, { name: "b", value: undefined }, { name: "c", value: undefined }, { name: "d", value: undefined }, { name: "", value: undefined }, ], expectedOutput: "fn(a: ?, b: ?, c: ?, d: ?)", }, testCase2: { arguments: [], expectedOutput: "fn()", }, testCase3: { arguments: [ { name: "a", value: undefined }, { name: "b", value: undefined }, { name: "", value: undefined }, { name: "", value: undefined }, ], expectedOutput: "fn(a: ?, b: ?)", }, }; it("function with 4 args", () => { expect(getFunctionsArgsType(testCases.testCase1.arguments)).toEqual( testCases.testCase1.expectedOutput, ); }); it("function with no args", () => { expect(getFunctionsArgsType(testCases.testCase2.arguments)).toEqual( testCases.testCase2.expectedOutput, ); }); it("function with 2 args", () => { expect(getFunctionsArgsType(testCases.testCase3.arguments)).toEqual( testCases.testCase3.expectedOutput, ); }); });
1,448
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/hooks/useDeepEffect.test.ts
import { renderHook } from "@testing-library/react-hooks"; import { useState } from "react"; import useDeepEffect from "./useDeepEffect"; describe(".useDeepEffect", () => { it("throws an error if using it with an empty array", () => { const { result } = renderHook(() => useDeepEffect(() => { "test"; }, []), ); expect(result.error).toMatchInlineSnapshot( `[Error: useDeepEffect should not be used with no dependencies. Use React.useEffect instead.]`, ); }); it("throws an error if using it with an array of only primitive values", () => { const { result } = renderHook(() => useDeepEffect(() => { "test"; }, [true, 1, "string"]), ); expect(result.error).toMatchInlineSnapshot( `[Error: useDeepEffect should not be used with dependencies that are all primitive values. Use React.useEffect instead.]`, ); }); it("production mode there are no errors thrown", () => { const env = process.env.NODE_ENV; // @ts-expect-error: Types are not available process.env.NODE_ENV = "production"; renderHook(() => useDeepEffect(() => { (""); }, [true, 1, "string"]), ); renderHook(() => useDeepEffect(() => { (""); }, []), ); // @ts-expect-error: Types are not available process.env.NODE_ENV = env; }); it("handles changing values as expected", () => { const callback = jest.fn(); let deps = [1, { a: "b" }, true]; const { rerender } = renderHook(() => useDeepEffect(callback, deps)); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); // no change rerender(); expect(callback).toHaveBeenCalledTimes(0); callback.mockClear(); // no-change (new object with same properties) deps = [1, { a: "b" }, true]; rerender(); expect(callback).toHaveBeenCalledTimes(0); callback.mockClear(); // change (new primitive value) deps = [2, { a: "b" }, true]; rerender(); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); // no-change rerender(); expect(callback).toHaveBeenCalledTimes(0); callback.mockClear(); // change (new primitive value) deps = [1, { a: "b" }, false]; rerender(); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); // change (new properties on object) deps = [1, { a: "c" }, false]; rerender(); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); }); it("works with deep object similarities/differences", () => { const callback = jest.fn(); let deps: Array<Record<string, unknown>> = [{ a: { b: { c: "d" } } }]; const { rerender } = renderHook(() => useDeepEffect(callback, deps)); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); // change primitive value deps = [{ a: { b: { c: "e" } } }]; rerender(); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); // no-change deps = [{ a: { b: { c: "e" } } }]; rerender(); expect(callback).toHaveBeenCalledTimes(0); callback.mockClear(); // add property deps = [{ a: { b: { c: "e" }, f: "g" } }]; rerender(); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); }); it("works with getDerivedStateFromProps", () => { const callback = jest.fn(); const { rerender } = renderHook( ({ a }: { a: number }) => { const [lastA, setLastA] = useState(a); const [c, setC] = useState(5); if (lastA !== a) { setLastA(a); setC(1); } useDeepEffect(callback, [{ a, c }]); }, { initialProps: { a: 1 } }, ); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); // change a, and reset c rerender({ a: 2 }); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); }); });
1,472
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils/hooks
petrpan-code/appsmithorg/appsmith/app/client/src/utils/hooks/useWidgetFocus/tabbable.test.ts
import { getNextTabbableDescendant } from "./tabbable"; describe("getNextTabbableDescendant", () => { it("should return undefined if no descendants are passed", () => { expect(getNextTabbableDescendant([])).toBeUndefined(); }); });
1,476
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/ChartWidget.test.ts
import { migrateChartWidgetLabelOrientationStaggerOption, migrateAddShowHideDataPointLabels, migrateDefaultValuesForCustomEChart, } from "./ChartWidget"; import type { DSLWidget } from "WidgetProvider/constants"; import type { ChartWidgetProps } from "widgets/ChartWidget/widget"; import { LabelOrientation } from "widgets/ChartWidget/constants"; const inputDSL: DSLWidget = { widgetId: "", widgetName: "canvas widget", type: "CANVAS_WIDGET", renderMode: "CANVAS", version: 1, parentColumnSpace: 1, parentRowSpace: 1, isLoading: false, topRow: 0, bottomRow: 0, leftColumn: 0, rightColumn: 0, children: [ { widgetId: "", widgetName: "chart widget", type: "CHART_WIDGET", renderMode: "CANVAS", version: 1, parentColumnSpace: 1, parentRowSpace: 1, isLoading: false, topRow: 0, bottomRow: 0, leftColumn: 0, rightColumn: 0, labelOrientation: LabelOrientation.STAGGER, allowScroll: true, children: [], }, ], }; describe("Migrate Label Orientation from type stagger to auto", () => { it("migrates label orientation from type stagger to auto", () => { const outputDSL = migrateChartWidgetLabelOrientationStaggerOption(inputDSL); const outputChartWidgetDSL = (outputDSL.children && outputDSL.children[0]) as ChartWidgetProps; expect(outputChartWidgetDSL.labelOrientation).toEqual("auto"); }); }); describe("Migrate Label show/hide property with respect to chart's allow scroll property", () => { it("if allow scroll property is false, it migrates label show/hide property to false", () => { const allowScroll = false; const dsl = JSON.parse(JSON.stringify(inputDSL)); const chartDSL = (dsl.children ?? [])[0]; chartDSL.allowScroll = allowScroll; expect(dsl.showDataPointLabel).toBeUndefined(); const outputDSL = migrateAddShowHideDataPointLabels(dsl); const outputChartWidgetDSL = (outputDSL.children && outputDSL.children[0]) as ChartWidgetProps; expect(outputChartWidgetDSL.showDataPointLabel).not.toBeUndefined(); expect(outputChartWidgetDSL.showDataPointLabel).toEqual(false); }); it("if allow scroll property is true, it migrates label show/hide property to true", () => { const allowScroll = true; const dsl = JSON.parse(JSON.stringify(inputDSL)); const chartDSL = (dsl.children ?? [])[0]; chartDSL.allowScroll = allowScroll; expect(dsl.showDataPointLabel).toBeUndefined(); const outputDSL = migrateAddShowHideDataPointLabels(dsl); const outputChartWidgetDSL = (outputDSL.children && outputDSL.children[0]) as ChartWidgetProps; expect(outputChartWidgetDSL.showDataPointLabel).not.toBeUndefined(); expect(outputChartWidgetDSL.showDataPointLabel).not.toBeNull(); expect(outputChartWidgetDSL.showDataPointLabel).toEqual(true); }); }); describe("Migrate Default Custom EChart configuration", () => { it("adds echart custom chart default configuration to existing charts", () => { const inputChartWidgetDSL = inputDSL.children?.[0] as ChartWidgetProps; expect(inputChartWidgetDSL.customEChartConfig).not.toBeDefined(); const outputDSL = migrateDefaultValuesForCustomEChart(inputDSL); const outputChartWidgetDSL = outputDSL.children?.[0] as ChartWidgetProps; expect(outputChartWidgetDSL.customEChartConfig).toBeDefined(); expect( Object.keys(outputChartWidgetDSL.customEChartConfig).length, ).toBeGreaterThan(0); }); });
1,478
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/ChartWidgetReskinningMigrations.test.ts
import type { DSLWidget } from "WidgetProvider/constants"; import { migrateChartWidgetReskinningData } from "./ChartWidgetReskinningMigrations"; const currentDslWithoutCustomConfig = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 4896, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1020, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 59, minHeight: 1292, dynamicTriggerPathList: [], parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Chart1", allowScroll: false, displayName: "Chart", iconSVG: "/static/media/icon.6adbe31ed817fc4bfd66f9f0a6fc105c.svg", searchTags: ["graph", "visuals", "visualisations"], topRow: 13, bottomRow: 45, parentRowSpace: 10, type: "CHART_WIDGET", hideCard: false, chartData: { xbhibr5ak2: { seriesName: "Sales", data: [ { x: "Product1", y: 20000, }, { x: "Product2", y: 22000, }, { x: "Product3", y: 32000, }, ], }, }, animateLoading: true, parentColumnSpace: 28.875, leftColumn: 5, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, ], key: "echv58ig42", isDeprecated: false, rightColumn: 23, widgetId: "jl53hd277f", isVisible: true, version: 1, parentId: "0", labelOrientation: "auto", renderMode: "CANVAS", isLoading: false, yAxisName: "Revenue($)", chartName: "Sales Report", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", xAxisName: "Product Line", chartType: "COLUMN_CHART", }, ], }; const expectedDslWithoutCustomConfig = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 4896, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1020, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 59, minHeight: 1292, dynamicTriggerPathList: [], parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Chart1", allowScroll: false, displayName: "Chart", iconSVG: "/static/media/icon.6adbe31ed817fc4bfd66f9f0a6fc105c.svg", searchTags: ["graph", "visuals", "visualisations"], topRow: 13, bottomRow: 45, parentRowSpace: 10, type: "CHART_WIDGET", hideCard: false, chartData: { xbhibr5ak2: { seriesName: "Sales", data: [ { x: "Product1", y: 20000, }, { x: "Product2", y: 22000, }, { x: "Product3", y: 32000, }, ], }, }, animateLoading: true, fontFamily: "{{appsmith.theme.fontFamily.appFont}}", parentColumnSpace: 28.875, leftColumn: 5, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, { key: "accentColor", }, { key: "fontFamily", }, ], key: "echv58ig42", isDeprecated: false, rightColumn: 23, widgetId: "jl53hd277f", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisible: true, version: 1, parentId: "0", labelOrientation: "auto", renderMode: "CANVAS", isLoading: false, yAxisName: "Revenue($)", chartName: "Sales Report", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", xAxisName: "Product Line", chartType: "COLUMN_CHART", }, ], }; describe("Chart Widget Reskinning Migration - ", () => { it("should add accentColor and fontFamily properties with Dynamic values (without customFusionChartConfig)", () => { const migratedDsl = migrateChartWidgetReskinningData( currentDslWithoutCustomConfig as unknown as DSLWidget, ); expect(migratedDsl).toEqual(expectedDslWithoutCustomConfig); }); });
1,483
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/CurrencyInputWidgetMigrations.test.ts
import type { DSLWidget } from "WidgetProvider/constants"; import { migrateCurrencyInputWidgetDefaultCurrencyCode, migrateInputWidgetShowStepArrows, } from "./CurrencyInputWidgetMigrations"; const oldDSLWithCurrencyCode = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [{ key: "currencyCode" }], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [{ key: "currencyCode" }], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", currencyCode: "{{'USD'}}", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const expectedDSLWithDefaultCurrencyCode = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [{ key: "defaultCurrencyCode" }], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [{ key: "defaultCurrencyCode" }], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", defaultCurrencyCode: "{{'USD'}}", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const oldDSLWithCurrencyCode2 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", currencyCode: "USD", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const expectedDSLWithDefaultCurrencyCode2 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", defaultCurrencyCode: "USD", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const oldDSLWithoutShowStepArrows = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "NUMBER", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [{ key: "defaultCurrencyCode" }], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [{ key: "defaultCurrencyCode" }], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", defaultCurrencyCode: "{{'USD'}}", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const expectedDSLWithShowStepArrows = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "NUMBER", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, showStepArrows: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [{ key: "defaultCurrencyCode" }], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [{ key: "defaultCurrencyCode" }], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, showStepArrows: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", defaultCurrencyCode: "{{'USD'}}", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; describe("CurrencyInputWidgetMigrations - ", () => { describe("migrateCurrencyInputWidgetDefaultCountryCode - ", () => { it("should test that its only migrating default country code with dynamic value", () => { expect( migrateCurrencyInputWidgetDefaultCurrencyCode( oldDSLWithCurrencyCode as unknown as DSLWidget, ), ).toEqual(expectedDSLWithDefaultCurrencyCode); }); it("should test that its only migrating default country code without dynamic value", () => { expect( migrateCurrencyInputWidgetDefaultCurrencyCode( oldDSLWithCurrencyCode2 as unknown as DSLWidget, ), ).toEqual(expectedDSLWithDefaultCurrencyCode2); }); }); describe("Input Widget for Number-Type and Currency Migration - ", () => { it("should test that its only migrating showStepArrows", () => { const migratedDsl = migrateInputWidgetShowStepArrows( oldDSLWithoutShowStepArrows as unknown as DSLWidget, ); expect(migratedDsl).toEqual(expectedDSLWithShowStepArrows); }); }); });
1,490
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/ModalWidget.test.ts
import { GridDefaults } from "constants/WidgetConstants"; import type { DSLWidget } from "WidgetProvider/constants"; import { migrateResizableModalWidgetProperties } from "./ModalWidget"; const inputDsl1: DSLWidget = { widgetName: "MainContainer", widgetId: "0", type: "CANVAS_WIDGET", version: 15, parentId: "", renderMode: "CANVAS", children: [ { widgetName: "modal", version: 1, type: "MODAL_WIDGET", size: "MODAL_SMALL", parentId: "0", widgetId: "yf8bhokz7d", renderMode: "CANVAS", parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }, ], parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }; const outputDsl1: DSLWidget = { widgetName: "MainContainer", widgetId: "0", type: "CANVAS_WIDGET", version: 15, parentId: "", renderMode: "CANVAS", children: [ { widgetName: "modal", version: 2, type: "MODAL_WIDGET", height: GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 24, width: 456, parentId: "0", widgetId: "yf8bhokz7d", renderMode: "CANVAS", parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }, ], parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }; const inputDsl2: DSLWidget = { widgetName: "MainContainer", widgetId: "0", type: "CANVAS_WIDGET", version: 15, parentId: "", renderMode: "CANVAS", children: [ { widgetName: "modal", version: 1, type: "MODAL_WIDGET", size: "MODAL_LARGE", parentId: "0", widgetId: "yf8bhokz7d", renderMode: "CANVAS", parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }, ], parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }; const outputDsl2: DSLWidget = { widgetName: "MainContainer", widgetId: "0", type: "CANVAS_WIDGET", version: 15, parentId: "", renderMode: "CANVAS", children: [ { widgetName: "modal", version: 2, type: "MODAL_WIDGET", height: GridDefaults.DEFAULT_GRID_ROW_HEIGHT * 60, width: 532, parentId: "0", widgetId: "yf8bhokz7d", renderMode: "CANVAS", parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }, ], parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }; const dsl3: DSLWidget = { widgetName: "MainContainer", widgetId: "0", type: "CANVAS_WIDGET", version: 15, parentId: "", renderMode: "CANVAS", children: [ { widgetName: "modal", version: 2, type: "MODAL_WIDGET", height: 500, width: 532, parentId: "0", widgetId: "yf8bhokz7d", renderMode: "CANVAS", parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }, ], parentColumnSpace: 0, parentRowSpace: 0, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, isLoading: false, }; describe("Migrate to Resizable Modal", () => { it("To test modal with type MODAL_SMALL", () => { const newDsl = migrateResizableModalWidgetProperties(inputDsl1); expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl1)); }); it("To test modal with type MODAL_SMALL", () => { const newDsl = migrateResizableModalWidgetProperties(inputDsl2); expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl2)); }); it("To test a migrated modal", () => { const newDsl = migrateResizableModalWidgetProperties(dsl3); expect(JSON.stringify(newDsl) === JSON.stringify(dsl3)); }); });
1,492
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/PhoneInputWidgetMigrations.test.ts
import type { DSLWidget } from "WidgetProvider/constants"; import { migratePhoneInputWidgetAllowFormatting, migratePhoneInputWidgetDefaultDialCode, } from "./PhoneInputWidgetMigrations"; const oldDSL = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", currencyCode: "USD", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const newDSL = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", currencyCode: "USD", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", allowFormatting: true, renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const oldDSLWithDialCode = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", currencyCode: "USD", }, { widgetName: "PhoneInput1", dialCode: "{{'+1'}}", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [{ key: "dialCode" }], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [{ key: "dialCode" }], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const expectedDSLWithDefaultDialCode = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", currencyCode: "USD", }, { widgetName: "PhoneInput1", defaultDialCode: "{{'+1'}}", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [{ key: "defaultDialCode" }], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [{ key: "defaultDialCode" }], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const oldDSLWithDialCode2 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", currencyCode: "USD", }, { widgetName: "PhoneInput1", dialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; const expectedDSLWithDefaultDialCode2 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1296, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1130, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 52, minHeight: 890, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action", "customColumn1"], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 2, bottomRow: 30, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 11, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "tezu035xfn", derivedColumns: { customColumn1: { index: 4, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "test", computedValue: "", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 45, textSize: "PARAGRAPH", widgetId: "l7p1322ix5", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, multiRowSelection: true, }, { widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595.svg", topRow: 33, bottomRow: 37, parentRowSpace: 10, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, resetOnSubmit: true, leftColumn: 11, labelStyle: "", inputType: "TEXT", isDisabled: false, key: "tj11un6vmd", isRequired: false, rightColumn: 31, widgetId: "whay9rh6bp", isVisible: true, label: "", version: 2, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { widgetName: "CurrencyInput1", displayName: "Currency Input", iconSVG: "/static/media/icon.01a1e03d.svg", topRow: 44, bottomRow: 48, parentRowSpace: 10, autoFocus: false, type: "CURRENCY_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], labelStyle: "", isDisabled: false, key: "4pdqazset5", isRequired: false, rightColumn: 31, widgetId: "0i6is5knem", isVisible: true, label: "", allowCurrencyChange: false, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, decimals: 0, iconAlign: "left", defaultText: "", currencyCode: "USD", }, { widgetName: "PhoneInput1", defaultDialCode: "+1", displayName: "Phone Input", iconSVG: "/static/media/icon.ec4f5c23.svg", topRow: 54, bottomRow: 58, parentRowSpace: 10, autoFocus: false, type: "PHONE_INPUT_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, dynamicPropertyPathList: [], dynamicTriggerPathList: [], resetOnSubmit: true, leftColumn: 11, dynamicBindingPathList: [], countryCode: "US", labelStyle: "", isDisabled: false, key: "hygs5twb8a", isRequired: false, rightColumn: 31, widgetId: "2hdejhkfe2", allowDialCodeChange: false, isVisible: true, label: "", version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, iconAlign: "left", defaultText: "", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container1", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas1", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, isDisabled: false, datePickerType: "DATE_PICKER", label: "", dateFormat: "YYYY-MM-DD HH:mm", widgetName: "DatePicker1", defaultDate: "2022-02-02T12:35:06.838Z", minDate: "1920-12-31T18:30:00.000Z", maxDate: "2121-12-31T18:29:00.000Z", version: 2, isRequired: false, closeOnSelection: true, shortcuts: false, firstDayOfWeek: 0, timePrecision: "minute", animateLoading: true, type: "DATE_PICKER_WIDGET2", hideCard: false, displayName: "DatePicker", key: "ot1g8a7wsy", iconSVG: "/static/media/icon.300e5ab8.svg", widgetId: "b40vzteeen", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 3, rightColumn: 41, topRow: 1, bottomRow: 5, parentId: "onbmx309sa", }, { isVisible: true, backgroundColor: "#FFFFFF", widgetName: "Container2", containerStyle: "card", borderColor: "transparent", borderWidth: "0", borderRadius: "0", boxShadow: "NONE", animateLoading: true, children: [ { isVisible: true, widgetName: "Canvas2", version: 1, detachFromLayout: true, type: "CANVAS_WIDGET", hideCard: true, displayName: "Canvas", key: "upcnljouz6", containerStyle: "none", canExtend: false, children: [ { isVisible: true, animateLoading: true, text: "Submit", buttonColor: "#03B365", buttonVariant: "PRIMARY", placement: "CENTER", widgetName: "Button1", isDisabled: false, isDefaultClickDisabled: true, recaptchaType: "V3", version: 1, type: "BUTTON_WIDGET", hideCard: false, displayName: "Button", key: "61pqdckhct", iconSVG: "/static/media/icon.cca02633.svg", widgetId: "viyg9naglg", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 4.9830322265625, parentRowSpace: 10, leftColumn: 4, rightColumn: 20, topRow: 3, bottomRow: 7, parentId: "847huqpwdl", }, ], minHeight: 400, widgetId: "847huqpwdl", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 173.0625, topRow: 0, bottomRow: 400, parentId: "p1czagf2h9", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "p1czagf2h9", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 7.2109375, parentRowSpace: 10, leftColumn: 4, rightColumn: 51, topRow: 8, bottomRow: 48, parentId: "onbmx309sa", }, ], minHeight: 400, widgetId: "onbmx309sa", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 481.5, topRow: 0, bottomRow: 500, parentId: "6v4urdv6p2", }, ], version: 1, type: "CONTAINER_WIDGET", hideCard: false, displayName: "Container", key: "parnsbxrsh", iconSVG: "/static/media/icon.1977dca3.svg", isCanvas: true, widgetId: "6v4urdv6p2", renderMode: "CANVAS", isLoading: false, parentColumnSpace: 20.0625, parentRowSpace: 10, leftColumn: 12, rightColumn: 36, topRow: 61, bottomRow: 111, parentId: "0", }, ], }; describe("PhoneInputWidgetMigrations - ", () => { describe("migratePhoneInputWidgetAllowFormatting - ", () => { it("should test that its only migrating allowFormatting", () => { expect( migratePhoneInputWidgetAllowFormatting(oldDSL as unknown as DSLWidget), ).toEqual(newDSL); }); }); describe("migratePhoneInputWidgetAllowFormatting - ", () => { it("should test that its only migrating default dial code with dynamic value", () => { expect( migratePhoneInputWidgetDefaultDialCode( oldDSLWithDialCode as unknown as DSLWidget, ), ).toEqual(expectedDSLWithDefaultDialCode); }); it("should test that its only migrating default dial code without dynamic value", () => { expect( migratePhoneInputWidgetDefaultDialCode( oldDSLWithDialCode2 as unknown as DSLWidget, ), ).toEqual(expectedDSLWithDefaultDialCode2); }); }); });
1,497
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/SelectWidget.test.ts
import type { DSLWidget } from "WidgetProvider/constants"; import { MigrateSelectTypeWidgetDefaultValue, migrateSelectWidgetAddSourceDataPropertyPathList, migrateSelectWidgetSourceDataBindingPathList, } from "./SelectWidget"; describe("MigrateSelectTypeWidgetDefaultValue", () => { describe("Select widget", () => { it("should check that defaultOptionValue is migrated when its in old format", () => { expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "{{moment()}}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment()))(select.options, select.serverSideFiltering) }}", }, ], }); expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "{{moment()}}{{moment()}}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment() + moment()))(select.options, select.serverSideFiltering) }}", }, ], }); }); it("should check that defaultOptionValue is not migrated when its in new format", () => { expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment()))(select.options, select.serverSideFiltering) }}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment()))(select.options, select.serverSideFiltering) }}", }, ], }); expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment() + moment()))(select.options, select.serverSideFiltering) }}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment() + moment()))(select.options, select.serverSideFiltering) }}", }, ], }); }); it("should check that defaultOptionValue is not migrated when its a static value", () => { expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "Green", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "SELECT_WIDGET", widgetName: "select", defaultOptionValue: "Green", }, ], }); }); }); describe("Multi Select widget", () => { it("should check that defaultOptionValue is migrated when its in old format", () => { expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "{{[moment()]}}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( [moment()]))(select.options, select.serverSideFiltering) }}", }, ], }); expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "{{moment()}}{{moment()}}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment() + moment()))(select.options, select.serverSideFiltering) }}", }, ], }); }); it("should check that defaultOptionValue is not migrated when its in new format", () => { expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( [moment()]))(select.options, select.serverSideFiltering) }}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( [moment()]))(select.options, select.serverSideFiltering) }}", }, ], }); expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment() + moment()))(select.options, select.serverSideFiltering) }}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment() + moment()))(select.options, select.serverSideFiltering) }}", }, ], }); }); it("should check that defaultOptionValue is not migrated when its a static value", () => { expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "[Green]", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: "[Green]", }, ], }); }); expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: ["Green"], }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "MULTI_SELECT_WIDGET_V2", widgetName: "select", defaultOptionValue: ["Green"], }, ], }); }); describe("other widget", () => { it("should left untouched", () => { expect( MigrateSelectTypeWidgetDefaultValue({ children: [ { type: "TABLE_WIDGET", widgetName: "select", defaultOptionValue: "{{[moment()]}}", }, ], } as any as DSLWidget), ).toEqual({ children: [ { type: "TABLE_WIDGET", widgetName: "select", defaultOptionValue: "{{[moment()]}}", }, ], }); }); }); it("should check that its not touching the dsl tree structure", () => { const input = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 4896, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 900, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 61, minHeight: 1292, dynamicTriggerPathList: [], parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action"], dynamicPropertyPathList: [], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd2acd22a31ea91cc37ea2a46c.svg", topRow: 2, bottomRow: 30, columnWidthMap: { task: 245, step: 62, status: 75, }, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET_V2", hideCard: false, inlineEditingSaveOption: "ROW_LEVEL", animateLoading: true, parentColumnSpace: 20.0625, dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, { key: "primaryColumns.action.buttonColor", }, { key: "primaryColumns.action.borderRadius", }, { key: "primaryColumns.action.boxShadow", }, { key: "accentColor", }, { key: "borderRadius", }, { key: "boxShadow", }, { key: "childStylesheet.button.buttonColor", }, { key: "childStylesheet.button.borderRadius", }, { key: "childStylesheet.menuButton.menuColor", }, { key: "childStylesheet.menuButton.borderRadius", }, { key: "childStylesheet.iconButton.buttonColor", }, { key: "childStylesheet.iconButton.borderRadius", }, { key: "childStylesheet.editActions.saveButtonColor", }, { key: "childStylesheet.editActions.saveBorderRadius", }, { key: "childStylesheet.editActions.discardButtonColor", }, { key: "childStylesheet.editActions.discardBorderRadius", }, ], leftColumn: 5, primaryColumns: { step: { index: 0, width: 150, id: "step", originalId: "step", alias: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "step", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["step"]))}}', validation: {}, labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", originalId: "task", alias: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "task", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["task"]))}}', validation: {}, labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", originalId: "status", alias: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "status", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["status"]))}}', validation: {}, labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", originalId: "action", alias: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["action"]))}}', validation: {}, labelColor: "#FFFFFF", buttonColor: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.colors.primaryColor))}}", borderRadius: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.borderRadius.appBorderRadius))}}", boxShadow: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( 'none'))}}", }, }, delimiter: ",", defaultSelectedRowIndex: 0, key: "11yw1d4v89", isDeprecated: false, rightColumn: 39, textSize: "0.875rem", widgetId: "154ekmu25d", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 1, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, childStylesheet: { button: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, menuButton: { menuColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, iconButton: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, editActions: { saveButtonColor: "{{appsmith.theme.colors.primaryColor}}", saveBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", discardButtonColor: "{{appsmith.theme.colors.primaryColor}}", discardBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, }, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", isVisiblePagination: true, defaultSelectedRowIndices: [0], verticalAlignment: "CENTER", }, { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Container1", borderColor: "transparent", isCanvas: true, displayName: "Container", iconSVG: "/static/media/icon.1977dca3370505e2db3a8e44cfd54907.svg", searchTags: ["div", "parent", "group"], topRow: 33, bottomRow: 88, parentRowSpace: 10, type: "CONTAINER_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, leftColumn: 5, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, ], children: [ { boxShadow: "none", widgetName: "Canvas1", displayName: "Canvas", topRow: 0, bottomRow: 530, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: false, hideCard: true, minHeight: 400, parentColumnSpace: 1, leftColumn: 0, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "accentColor", }, ], children: [ { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Form1", isCanvas: true, displayName: "Form", iconSVG: "/static/media/icon.ea3e08d130e59c56867ae40114c10eed.svg", searchTags: ["group"], topRow: 2, bottomRow: 42, parentRowSpace: 10, type: "FORM_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 10.345703125, leftColumn: 4, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, ], children: [ { boxShadow: "none", widgetName: "Canvas2", displayName: "Canvas", topRow: 0, bottomRow: 390, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: false, hideCard: true, minHeight: 400, parentColumnSpace: 1, leftColumn: 0, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "accentColor", }, ], children: [ { widgetName: "Text1", displayName: "Text", iconSVG: "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg", searchTags: ["typography", "paragraph", "label"], topRow: 1, bottomRow: 5, type: "TEXT_WIDGET", hideCard: false, animateLoading: true, overflow: "NONE", fontFamily: "{{appsmith.theme.fontFamily.appFont}}", leftColumn: 1.5, dynamicBindingPathList: [ { key: "fontFamily", }, { key: "borderRadius", }, ], shouldTruncate: false, truncateButtonColor: "#FFC13D", text: "Form", key: "5rfbzu1cpv", isDeprecated: false, rightColumn: 25.5, textAlign: "LEFT", widgetId: "c6xgdbotnb", isVisible: true, fontStyle: "BOLD", textColor: "#231F20", version: 1, parentId: "a4yu9qdsd3", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", fontSize: "1.25rem", }, { resetFormOnClick: true, boxShadow: "none", widgetName: "Button1", buttonColor: "{{appsmith.theme.colors.primaryColor}}", displayName: "Button", iconSVG: "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", searchTags: ["click", "submit"], topRow: 33, bottomRow: 37, type: "BUTTON_WIDGET", hideCard: false, animateLoading: true, leftColumn: 46, dynamicBindingPathList: [ { key: "buttonColor", }, { key: "borderRadius", }, ], text: "Submit", isDisabled: false, key: "v5rdaw9rk9", isDeprecated: false, rightColumn: 62, isDefaultClickDisabled: true, widgetId: "ezkuystufr", isVisible: true, recaptchaType: "V3", version: 1, parentId: "a4yu9qdsd3", renderMode: "CANVAS", isLoading: false, disabledWhenInvalid: true, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", buttonVariant: "PRIMARY", placement: "CENTER", }, { resetFormOnClick: true, boxShadow: "none", widgetName: "Button2", buttonColor: "{{appsmith.theme.colors.primaryColor}}", displayName: "Button", iconSVG: "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", searchTags: ["click", "submit"], topRow: 33, bottomRow: 37, type: "BUTTON_WIDGET", hideCard: false, animateLoading: true, leftColumn: 30, dynamicBindingPathList: [ { key: "buttonColor", }, { key: "borderRadius", }, ], text: "Reset", isDisabled: false, key: "v5rdaw9rk9", isDeprecated: false, rightColumn: 46, isDefaultClickDisabled: true, widgetId: "8zd8nvk2fs", isVisible: true, recaptchaType: "V3", version: 1, parentId: "a4yu9qdsd3", renderMode: "CANVAS", isLoading: false, disabledWhenInvalid: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", buttonVariant: "SECONDARY", placement: "CENTER", }, { boxShadow: "none", widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595da61a34f563dba82adeb06ec.svg", searchTags: [ "form", "text input", "number", "textarea", ], topRow: 7, bottomRow: 11, parentRowSpace: 10, labelWidth: 5, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 8.578338623046875, resetOnSubmit: true, leftColumn: 1, dynamicBindingPathList: [ { key: "accentColor", }, { key: "borderRadius", }, ], labelPosition: "Left", labelStyle: "", inputType: "TEXT", isDisabled: false, key: "mk8njmq8tm", labelTextSize: "0.875rem", isRequired: false, isDeprecated: false, rightColumn: 21, widgetId: "4emr5oa46o", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisible: true, label: "Label", version: 2, parentId: "a4yu9qdsd3", labelAlignment: "left", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", iconAlign: "left", defaultText: "", }, { boxShadow: "none", widgetName: "Select1", isFilterable: true, displayName: "Select", iconSVG: "/static/media/icon.bd99caba5853ad71e4b3d8daffacb3a2.svg", labelText: "Label", searchTags: ["dropdown"], topRow: 14, bottomRow: 18, parentRowSpace: 10, labelWidth: 5, type: "SELECT_WIDGET", serverSideFiltering: false, hideCard: false, defaultOptionValue: "{{moment()}}", animateLoading: true, parentColumnSpace: 8.578338623046875, leftColumn: 0, dynamicBindingPathList: [ { key: "accentColor", }, { key: "borderRadius", }, ], labelPosition: "Left", options: [ { label: "Blue", value: "BLUE", }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, ], placeholderText: "Select option", isDisabled: false, key: "3m7x2hnrkc", labelTextSize: "0.875rem", isRequired: false, isDeprecated: false, rightColumn: 20, widgetId: "6awuifuxy3", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisible: true, version: 1, parentId: "a4yu9qdsd3", labelAlignment: "left", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, { boxShadow: "none", widgetName: "MultiSelect1", isFilterable: true, displayName: "MultiSelect", iconSVG: "/static/media/icon.a3495809ae48291a64404f3bb04b0e69.svg", labelText: "Label", searchTags: ["dropdown", "tags"], topRow: 21, bottomRow: 25, parentRowSpace: 10, labelWidth: 5, type: "MULTI_SELECT_WIDGET_V2", serverSideFiltering: false, hideCard: false, defaultOptionValue: "{{[moment()]}}", animateLoading: true, parentColumnSpace: 8.578338623046875, leftColumn: 0, dynamicBindingPathList: [ { key: "accentColor", }, { key: "borderRadius", }, ], labelPosition: "Left", options: [ { label: "Blue", value: "BLUE", }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, ], placeholderText: "Select option(s)", isDisabled: false, key: "hzfum4zki4", labelTextSize: "0.875rem", isRequired: false, isDeprecated: false, rightColumn: 23, widgetId: "4gtzutx5cm", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisible: true, version: 1, parentId: "a4yu9qdsd3", labelAlignment: "left", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, ], key: "2vj82fyk6w", isDeprecated: false, rightColumn: 248.296875, detachFromLayout: true, widgetId: "a4yu9qdsd3", accentColor: "{{appsmith.theme.colors.primaryColor}}", containerStyle: "none", isVisible: true, version: 1, parentId: "quvculga8z", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, ], key: "64fkw5w3ne", backgroundColor: "#FFFFFF", isDeprecated: false, rightColumn: 59, widgetId: "quvculga8z", isVisible: true, parentId: "hfab4ag2fr", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, { widgetName: "Text2", displayName: "Text", iconSVG: "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg", searchTags: ["typography", "paragraph", "label"], topRow: 45, bottomRow: 51, parentRowSpace: 10, type: "TEXT_WIDGET", hideCard: false, animateLoading: true, overflow: "NONE", fontFamily: "{{appsmith.theme.fontFamily.appFont}}", parentColumnSpace: 10.345703125, leftColumn: 12, dynamicBindingPathList: [ { key: "fontFamily", }, { key: "borderRadius", }, ], shouldTruncate: false, truncateButtonColor: "#FFC13D", text: "Label", key: "xosgai8vfh", isDeprecated: false, rightColumn: 51, textAlign: "LEFT", widgetId: "i5t134gcz2", isVisible: true, fontStyle: "BOLD", textColor: "#231F20", version: 1, parentId: "hfab4ag2fr", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", fontSize: "1rem", }, ], key: "du5dxsnp7w", isDeprecated: false, rightColumn: 481.5, detachFromLayout: true, widgetId: "hfab4ag2fr", accentColor: "{{appsmith.theme.colors.primaryColor}}", containerStyle: "none", isVisible: true, version: 1, parentId: "3zdzo27neb", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, ], borderWidth: "0", key: "y2bj1fyd3j", backgroundColor: "#FFFFFF", isDeprecated: false, rightColumn: 39, widgetId: "3zdzo27neb", containerStyle: "card", isVisible: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, ], }; const output = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 4896, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 900, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 61, minHeight: 1292, dynamicTriggerPathList: [], parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action"], dynamicPropertyPathList: [], isVisibleDownload: true, displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd2acd22a31ea91cc37ea2a46c.svg", topRow: 2, bottomRow: 30, columnWidthMap: { task: 245, step: 62, status: 75, }, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET_V2", hideCard: false, inlineEditingSaveOption: "ROW_LEVEL", animateLoading: true, parentColumnSpace: 20.0625, dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, { key: "primaryColumns.action.buttonColor", }, { key: "primaryColumns.action.borderRadius", }, { key: "primaryColumns.action.boxShadow", }, { key: "accentColor", }, { key: "borderRadius", }, { key: "boxShadow", }, { key: "childStylesheet.button.buttonColor", }, { key: "childStylesheet.button.borderRadius", }, { key: "childStylesheet.menuButton.menuColor", }, { key: "childStylesheet.menuButton.borderRadius", }, { key: "childStylesheet.iconButton.buttonColor", }, { key: "childStylesheet.iconButton.borderRadius", }, { key: "childStylesheet.editActions.saveButtonColor", }, { key: "childStylesheet.editActions.saveBorderRadius", }, { key: "childStylesheet.editActions.discardButtonColor", }, { key: "childStylesheet.editActions.discardBorderRadius", }, ], leftColumn: 5, primaryColumns: { step: { index: 0, width: 150, id: "step", originalId: "step", alias: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "step", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["step"]))}}', validation: {}, labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", originalId: "task", alias: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "task", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["task"]))}}', validation: {}, labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", originalId: "status", alias: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "status", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["status"]))}}', validation: {}, labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", originalId: "action", alias: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["action"]))}}', validation: {}, labelColor: "#FFFFFF", buttonColor: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.colors.primaryColor))}}", borderRadius: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.borderRadius.appBorderRadius))}}", boxShadow: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( 'none'))}}", }, }, delimiter: ",", defaultSelectedRowIndex: 0, key: "11yw1d4v89", isDeprecated: false, rightColumn: 39, textSize: "0.875rem", widgetId: "154ekmu25d", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 1, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, childStylesheet: { button: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, menuButton: { menuColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, iconButton: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, editActions: { saveButtonColor: "{{appsmith.theme.colors.primaryColor}}", saveBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", discardButtonColor: "{{appsmith.theme.colors.primaryColor}}", discardBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, }, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", isVisiblePagination: true, defaultSelectedRowIndices: [0], verticalAlignment: "CENTER", }, { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Container1", borderColor: "transparent", isCanvas: true, displayName: "Container", iconSVG: "/static/media/icon.1977dca3370505e2db3a8e44cfd54907.svg", searchTags: ["div", "parent", "group"], topRow: 33, bottomRow: 88, parentRowSpace: 10, type: "CONTAINER_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 20.0625, leftColumn: 5, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, ], children: [ { boxShadow: "none", widgetName: "Canvas1", displayName: "Canvas", topRow: 0, bottomRow: 530, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: false, hideCard: true, minHeight: 400, parentColumnSpace: 1, leftColumn: 0, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "accentColor", }, ], children: [ { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Form1", isCanvas: true, displayName: "Form", iconSVG: "/static/media/icon.ea3e08d130e59c56867ae40114c10eed.svg", searchTags: ["group"], topRow: 2, bottomRow: 42, parentRowSpace: 10, type: "FORM_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 10.345703125, leftColumn: 4, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, ], children: [ { boxShadow: "none", widgetName: "Canvas2", displayName: "Canvas", topRow: 0, bottomRow: 390, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: false, hideCard: true, minHeight: 400, parentColumnSpace: 1, leftColumn: 0, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "accentColor", }, ], children: [ { widgetName: "Text1", displayName: "Text", iconSVG: "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg", searchTags: ["typography", "paragraph", "label"], topRow: 1, bottomRow: 5, type: "TEXT_WIDGET", hideCard: false, animateLoading: true, overflow: "NONE", fontFamily: "{{appsmith.theme.fontFamily.appFont}}", leftColumn: 1.5, dynamicBindingPathList: [ { key: "fontFamily", }, { key: "borderRadius", }, ], shouldTruncate: false, truncateButtonColor: "#FFC13D", text: "Form", key: "5rfbzu1cpv", isDeprecated: false, rightColumn: 25.5, textAlign: "LEFT", widgetId: "c6xgdbotnb", isVisible: true, fontStyle: "BOLD", textColor: "#231F20", version: 1, parentId: "a4yu9qdsd3", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", fontSize: "1.25rem", }, { resetFormOnClick: true, boxShadow: "none", widgetName: "Button1", buttonColor: "{{appsmith.theme.colors.primaryColor}}", displayName: "Button", iconSVG: "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", searchTags: ["click", "submit"], topRow: 33, bottomRow: 37, type: "BUTTON_WIDGET", hideCard: false, animateLoading: true, leftColumn: 46, dynamicBindingPathList: [ { key: "buttonColor", }, { key: "borderRadius", }, ], text: "Submit", isDisabled: false, key: "v5rdaw9rk9", isDeprecated: false, rightColumn: 62, isDefaultClickDisabled: true, widgetId: "ezkuystufr", isVisible: true, recaptchaType: "V3", version: 1, parentId: "a4yu9qdsd3", renderMode: "CANVAS", isLoading: false, disabledWhenInvalid: true, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", buttonVariant: "PRIMARY", placement: "CENTER", }, { resetFormOnClick: true, boxShadow: "none", widgetName: "Button2", buttonColor: "{{appsmith.theme.colors.primaryColor}}", displayName: "Button", iconSVG: "/static/media/icon.cca026338f1c8eb6df8ba03d084c2fca.svg", searchTags: ["click", "submit"], topRow: 33, bottomRow: 37, type: "BUTTON_WIDGET", hideCard: false, animateLoading: true, leftColumn: 30, dynamicBindingPathList: [ { key: "buttonColor", }, { key: "borderRadius", }, ], text: "Reset", isDisabled: false, key: "v5rdaw9rk9", isDeprecated: false, rightColumn: 46, isDefaultClickDisabled: true, widgetId: "8zd8nvk2fs", isVisible: true, recaptchaType: "V3", version: 1, parentId: "a4yu9qdsd3", renderMode: "CANVAS", isLoading: false, disabledWhenInvalid: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", buttonVariant: "SECONDARY", placement: "CENTER", }, { boxShadow: "none", widgetName: "Input1", displayName: "Input", iconSVG: "/static/media/icon.9f505595da61a34f563dba82adeb06ec.svg", searchTags: [ "form", "text input", "number", "textarea", ], topRow: 7, bottomRow: 11, parentRowSpace: 10, labelWidth: 5, autoFocus: false, type: "INPUT_WIDGET_V2", hideCard: false, animateLoading: true, parentColumnSpace: 8.578338623046875, resetOnSubmit: true, leftColumn: 1, dynamicBindingPathList: [ { key: "accentColor", }, { key: "borderRadius", }, ], labelPosition: "Left", labelStyle: "", inputType: "TEXT", isDisabled: false, key: "mk8njmq8tm", labelTextSize: "0.875rem", isRequired: false, isDeprecated: false, rightColumn: 21, widgetId: "4emr5oa46o", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisible: true, label: "Label", version: 2, parentId: "a4yu9qdsd3", labelAlignment: "left", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", iconAlign: "left", defaultText: "", }, { boxShadow: "none", widgetName: "Select1", isFilterable: true, displayName: "Select", iconSVG: "/static/media/icon.bd99caba5853ad71e4b3d8daffacb3a2.svg", labelText: "Label", searchTags: ["dropdown"], topRow: 14, bottomRow: 18, parentRowSpace: 10, labelWidth: 5, type: "SELECT_WIDGET", serverSideFiltering: false, hideCard: false, defaultOptionValue: "{{ ((options, serverSideFiltering) => ( moment()))(Select1.options, Select1.serverSideFiltering) }}", animateLoading: true, parentColumnSpace: 8.578338623046875, leftColumn: 0, dynamicBindingPathList: [ { key: "accentColor", }, { key: "borderRadius", }, ], labelPosition: "Left", options: [ { label: "Blue", value: "BLUE", }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, ], placeholderText: "Select option", isDisabled: false, key: "3m7x2hnrkc", labelTextSize: "0.875rem", isRequired: false, isDeprecated: false, rightColumn: 20, widgetId: "6awuifuxy3", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisible: true, version: 1, parentId: "a4yu9qdsd3", labelAlignment: "left", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, { boxShadow: "none", widgetName: "MultiSelect1", isFilterable: true, displayName: "MultiSelect", iconSVG: "/static/media/icon.a3495809ae48291a64404f3bb04b0e69.svg", labelText: "Label", searchTags: ["dropdown", "tags"], topRow: 21, bottomRow: 25, parentRowSpace: 10, labelWidth: 5, type: "MULTI_SELECT_WIDGET_V2", serverSideFiltering: false, hideCard: false, defaultOptionValue: "{{ ((options, serverSideFiltering) => ( [moment()]))(MultiSelect1.options, MultiSelect1.serverSideFiltering) }}", animateLoading: true, parentColumnSpace: 8.578338623046875, leftColumn: 0, dynamicBindingPathList: [ { key: "accentColor", }, { key: "borderRadius", }, ], labelPosition: "Left", options: [ { label: "Blue", value: "BLUE", }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, ], placeholderText: "Select option(s)", isDisabled: false, key: "hzfum4zki4", labelTextSize: "0.875rem", isRequired: false, isDeprecated: false, rightColumn: 23, widgetId: "4gtzutx5cm", accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisible: true, version: 1, parentId: "a4yu9qdsd3", labelAlignment: "left", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, ], key: "2vj82fyk6w", isDeprecated: false, rightColumn: 248.296875, detachFromLayout: true, widgetId: "a4yu9qdsd3", accentColor: "{{appsmith.theme.colors.primaryColor}}", containerStyle: "none", isVisible: true, version: 1, parentId: "quvculga8z", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, ], key: "64fkw5w3ne", backgroundColor: "#FFFFFF", isDeprecated: false, rightColumn: 59, widgetId: "quvculga8z", isVisible: true, parentId: "hfab4ag2fr", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, { widgetName: "Text2", displayName: "Text", iconSVG: "/static/media/icon.97c59b523e6f70ba6f40a10fc2c7c5b5.svg", searchTags: ["typography", "paragraph", "label"], topRow: 45, bottomRow: 51, parentRowSpace: 10, type: "TEXT_WIDGET", hideCard: false, animateLoading: true, overflow: "NONE", fontFamily: "{{appsmith.theme.fontFamily.appFont}}", parentColumnSpace: 10.345703125, leftColumn: 12, dynamicBindingPathList: [ { key: "fontFamily", }, { key: "borderRadius", }, ], shouldTruncate: false, truncateButtonColor: "#FFC13D", text: "Label", key: "xosgai8vfh", isDeprecated: false, rightColumn: 51, textAlign: "LEFT", widgetId: "i5t134gcz2", isVisible: true, fontStyle: "BOLD", textColor: "#231F20", version: 1, parentId: "hfab4ag2fr", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", fontSize: "1rem", }, ], key: "du5dxsnp7w", isDeprecated: false, rightColumn: 481.5, detachFromLayout: true, widgetId: "hfab4ag2fr", accentColor: "{{appsmith.theme.colors.primaryColor}}", containerStyle: "none", isVisible: true, version: 1, parentId: "3zdzo27neb", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, ], borderWidth: "0", key: "y2bj1fyd3j", backgroundColor: "#FFFFFF", isDeprecated: false, rightColumn: 39, widgetId: "3zdzo27neb", containerStyle: "card", isVisible: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, ], }; expect( MigrateSelectTypeWidgetDefaultValue(input as any as DSLWidget), ).toEqual(output); }); }); describe("migrateSelectWidgetSourceDataBindingPathList", () => { test("should test that options in dynamicBindingPathList is getting replaced with sourceData", () => { const result = migrateSelectWidgetSourceDataBindingPathList({ children: [ { type: "TABLE_WIDGET_V2", options: [], dynamicBindingPathList: [ { key: "optionValue", }, { key: "options", }, { key: "optionLabel", }, ], }, { type: "SELECT_WIDGET", options: [], dynamicBindingPathList: [ { key: "optionValue", }, { key: "options", }, { key: "optionLabel", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicBindingPathList: [ { key: "optionLabel", }, { key: "optionValue", }, { key: "options", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicBindingPathList: [ { key: "optionLabel", }, { key: "optionValue", }, ], }, ], } as any as DSLWidget); expect(result).toEqual({ children: [ { type: "TABLE_WIDGET_V2", options: [], dynamicBindingPathList: [ { key: "optionValue", }, { key: "options", }, { key: "optionLabel", }, ], }, { type: "SELECT_WIDGET", options: [], dynamicBindingPathList: [ { key: "optionValue", }, { key: "sourceData", }, { key: "optionLabel", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicBindingPathList: [ { key: "optionLabel", }, { key: "optionValue", }, { key: "sourceData", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicBindingPathList: [ { key: "optionLabel", }, { key: "optionValue", }, ], }, ], }); }); }); describe("migrateSelectWidgetAddSourceDataPropertyPathList", () => { test("should test that sourceData is added to the dynamicPropertyPathList", () => { const result = migrateSelectWidgetAddSourceDataPropertyPathList({ children: [ { type: "TABLE_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "optionValue", }, { key: "sourceData", }, { key: "optionLabel", }, ], }, { type: "TABLE_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "optionValue", }, { key: "optionLabel", }, ], }, { type: "TABLE_WIDGET_V2", options: [], }, { type: "SELECT_WIDGET", options: [], dynamicPropertyPathList: [ { key: "optionValue", }, { key: "sourceData", }, { key: "optionLabel", }, ], }, { type: "SELECT_WIDGET", options: [], dynamicPropertyPathList: [ { key: "optionValue", }, { key: "optionLabel", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "optionLabel", }, { key: "sourceData", }, { key: "optionValue", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "optionLabel", }, { key: "optionValue", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], }, ], } as any as DSLWidget); expect(result).toEqual({ children: [ { type: "TABLE_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "optionValue", }, { key: "sourceData", }, { key: "optionLabel", }, ], }, { type: "TABLE_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "optionValue", }, { key: "optionLabel", }, ], }, { type: "TABLE_WIDGET_V2", options: [], }, { type: "SELECT_WIDGET", options: [], dynamicPropertyPathList: [ { key: "optionValue", }, { key: "sourceData", }, { key: "optionLabel", }, ], }, { type: "SELECT_WIDGET", options: [], dynamicPropertyPathList: [ { key: "optionValue", }, { key: "optionLabel", }, { key: "sourceData", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "optionLabel", }, { key: "sourceData", }, { key: "optionValue", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "optionLabel", }, { key: "optionValue", }, { key: "sourceData", }, ], }, { type: "MULTI_SELECT_WIDGET_V2", options: [], dynamicPropertyPathList: [ { key: "sourceData", }, ], }, ], }); }); });
1,499
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/TableWidget.test.ts
import { cloneDeep } from "lodash"; import type { DSLWidget } from "WidgetProvider/constants"; import { tableWidgetPropertyPaneMigrations, migrateTableWidgetParentRowSpaceProperty, migrateTableWidgetHeaderVisibilityProperties, migrateTableWidgetSelectedRowBindings, migrateTableSanitizeColumnKeys, migrateTableWidgetNumericColumnName, migrateTableWidgetV2ValidationBinding, migrateTableWidgetV2SelectOption, migrateTableWidgetTableDataJsMode, } from "./TableWidget"; const input1: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table1", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 40, leftColumn: 0, rightColumn: 8, topRow: 19, bottomRow: 26, parentId: "0", widgetId: "fs785w9gcy", dynamicBindingPathList: [], renderMode: "CANVAS", version: 1, }, ], }; const input2: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table2", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 40, leftColumn: 0, rightColumn: 8, topRow: 28, bottomRow: 35, parentId: "0", widgetId: "l9i1e8ybkm", dynamicBindingPathList: [], dynamicTriggerPathList: [{ key: "columnActions" }], columnActions: [ { label: "Test", id: "ezooq966rd", actionPayloads: [], dynamicTrigger: "{{showAlert('test','success')}}", }, { label: "Fail", id: "1k8nkay5r6", actionPayloads: [], dynamicTrigger: "{{showAlert('Fail','error')}}", }, ], renderMode: "CANVAS", version: 1, }, ], }; const input3: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table3", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 40, leftColumn: 0, rightColumn: 8, topRow: 37, bottomRow: 44, parentId: "0", widgetId: "8mkidz550s", dynamicBindingPathList: [], dynamicTriggerPathList: [ { key: "onRowSelected" }, { key: "onSearchTextChanged" }, ], onRowSelected: "{{showAlert('test','success')}}", onSearchTextChanged: "{{showAlert('fail','error')}}", renderMode: "CANVAS", version: 1, }, ], }; const output1 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table1", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 40, leftColumn: 0, rightColumn: 8, topRow: 19, bottomRow: 26, parentId: "0", widgetId: "fs785w9gcy", dynamicBindingPathList: [], primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "id", computedValue: "", }, email: { index: 1, width: 150, id: "email", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "email", computedValue: "", }, userName: { index: 2, width: 150, id: "userName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "userName", computedValue: "", }, productName: { index: 3, width: 150, id: "productName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "productName", computedValue: "", }, orderAmount: { index: 4, width: 150, id: "orderAmount", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "orderAmount", computedValue: "", }, }, textSize: "PARAGRAPH", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", renderMode: "CANVAS", version: 1, }, ], }; const output2 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table2", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 40, leftColumn: 0, rightColumn: 8, topRow: 28, bottomRow: 35, parentId: "0", widgetId: "l9i1e8ybkm", dynamicBindingPathList: [], dynamicTriggerPathList: [ { key: "columnActions" }, { key: "primaryColumns.customColumn1.onClick" }, { key: "primaryColumns.customColumn2.onClick" }, ], columnActions: [ { label: "Test", id: "ezooq966rd", actionPayloads: [], dynamicTrigger: "{{showAlert('test','success')}}", }, { label: "Fail", id: "1k8nkay5r6", actionPayloads: [], dynamicTrigger: "{{showAlert('Fail','error')}}", }, ], primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "id", computedValue: "", }, email: { index: 1, width: 150, id: "email", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "email", computedValue: "", }, userName: { index: 2, width: 150, id: "userName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "userName", computedValue: "", }, productName: { index: 3, width: 150, id: "productName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "productName", computedValue: "", }, orderAmount: { index: 4, width: 150, id: "orderAmount", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "orderAmount", computedValue: "", }, customColumn1: { index: 5, width: 150, id: "ezooq966rd", label: "Test", columnType: "button", isVisible: true, isDerived: true, buttonLabel: "Test", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", onClick: "{{showAlert('test','success')}}", }, customColumn2: { index: 6, width: 150, id: "1k8nkay5r6", label: "Fail", columnType: "button", isVisible: true, isDerived: true, buttonLabel: "Fail", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", onClick: "{{showAlert('Fail','error')}}", }, }, textSize: "PARAGRAPH", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", renderMode: "CANVAS", version: 1, }, ], }; const output3 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table3", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 40, leftColumn: 0, rightColumn: 8, topRow: 37, bottomRow: 44, parentId: "0", widgetId: "8mkidz550s", dynamicBindingPathList: [], dynamicTriggerPathList: [ { key: "onRowSelected" }, { key: "onSearchTextChanged" }, ], onRowSelected: "{{showAlert('test','success')}}", onSearchTextChanged: "{{showAlert('fail','error')}}", primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "id", computedValue: "", }, email: { index: 1, width: 150, id: "email", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "email", computedValue: "", }, userName: { index: 2, width: 150, id: "userName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "userName", computedValue: "", }, productName: { index: 3, width: 150, id: "productName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "productName", computedValue: "", }, orderAmount: { index: 4, width: 150, id: "orderAmount", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "orderAmount", computedValue: "", }, }, textSize: "PARAGRAPH", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", renderMode: "CANVAS", version: 1, }, ], }; describe("Table Widget Property Pane Upgrade", () => { it("To test primaryColumns are created for a simple table", () => { const newDsl = tableWidgetPropertyPaneMigrations(input1); expect(JSON.stringify(newDsl) === JSON.stringify(output1)); }); it("To test columnActions are migrated derived primaryColumns", () => { const newDsl = tableWidgetPropertyPaneMigrations(input2); expect(JSON.stringify(newDsl) === JSON.stringify(output2)); }); it("To test table action are migrated", () => { const newDsl = tableWidgetPropertyPaneMigrations(input3); expect(JSON.stringify(newDsl) === JSON.stringify(output3)); }); it("To test table parentRowSpace is updated", () => { const inputDsl: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table1", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 40, leftColumn: 0, rightColumn: 8, topRow: 19, bottomRow: 26, parentId: "0", widgetId: "fs785w9gcy", dynamicBindingPathList: [], primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "id", computedValue: "", }, email: { index: 1, width: 150, id: "email", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "email", computedValue: "", }, userName: { index: 2, width: 150, id: "userName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "userName", computedValue: "", }, productName: { index: 3, width: 150, id: "productName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "productName", computedValue: "", }, orderAmount: { index: 4, width: 150, id: "orderAmount", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "orderAmount", computedValue: "", }, }, textSize: "PARAGRAPH", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", renderMode: "CANVAS", version: 1, }, ], }; const outputDsl: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table1", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 10, leftColumn: 0, rightColumn: 8, topRow: 19, bottomRow: 26, parentId: "0", widgetId: "fs785w9gcy", dynamicBindingPathList: [], primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "id", computedValue: "", }, email: { index: 1, width: 150, id: "email", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "email", computedValue: "", }, userName: { index: 2, width: 150, id: "userName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "userName", computedValue: "", }, productName: { index: 3, width: 150, id: "productName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "productName", computedValue: "", }, orderAmount: { index: 4, width: 150, id: "orderAmount", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "orderAmount", computedValue: "", }, }, textSize: "PARAGRAPH", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", renderMode: "CANVAS", version: 1, }, ], }; const newDsl = migrateTableWidgetParentRowSpaceProperty(inputDsl); expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl)); }); it("TableWidget : should update header options visibilities", () => { const inputDsl: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table1", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 40, leftColumn: 0, rightColumn: 8, topRow: 19, bottomRow: 26, parentId: "0", widgetId: "fs785w9gcy", dynamicBindingPathList: [], primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "id", computedValue: "", }, email: { index: 1, width: 150, id: "email", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "email", computedValue: "", }, userName: { index: 2, width: 150, id: "userName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "userName", computedValue: "", }, productName: { index: 3, width: 150, id: "productName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "productName", computedValue: "", }, orderAmount: { index: 4, width: 150, id: "orderAmount", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "orderAmount", computedValue: "", }, }, textSize: "PARAGRAPH", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", renderMode: "CANVAS", version: 1, }, ], }; const outputDsl: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1840, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 7, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, label: "Data", widgetName: "Table1", searchKey: "", tableData: '[\n {\n "id": 2381224,\n "email": "[email protected]",\n "userName": "Michael Lawson",\n "productName": "Chicken Sandwich",\n "orderAmount": 4.99\n },\n {\n "id": 2736212,\n "email": "[email protected]",\n "userName": "Lindsay Ferguson",\n "productName": "Tuna Salad",\n "orderAmount": 9.99\n },\n {\n "id": 6788734,\n "email": "[email protected]",\n "userName": "Tobias Funke",\n "productName": "Beef steak",\n "orderAmount": 19.99\n }\n]', type: "TABLE_WIDGET", isLoading: false, parentColumnSpace: 74, parentRowSpace: 10, leftColumn: 0, rightColumn: 8, topRow: 19, bottomRow: 26, parentId: "0", widgetId: "fs785w9gcy", dynamicBindingPathList: [], primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "id", computedValue: "", }, email: { index: 1, width: 150, id: "email", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "email", computedValue: "", }, userName: { index: 2, width: 150, id: "userName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "userName", computedValue: "", }, productName: { index: 3, width: 150, id: "productName", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "productName", computedValue: "", }, orderAmount: { index: 4, width: 150, id: "orderAmount", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textColor: "#231F20", textSize: "PARAGRAPH", fontStyle: "REGULAR", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "orderAmount", computedValue: "", }, }, textSize: "PARAGRAPH", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", renderMode: "CANVAS", isVisibleSearch: true, isVisibleFilters: true, isVisibleDownload: true, isVisibleCompactMode: true, isVisiblePagination: true, version: 1, }, ], }; const newDsl = migrateTableWidgetHeaderVisibilityProperties(inputDsl); expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl)); }); }); describe("Table Widget Migration - #migrateTableSanitizeColumnKeys", () => { it("sanitizes primaryColumns, dynamicBindingPathList, columnOrder", () => { const inputDsl = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1080, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 980, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 34, minHeight: 860, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["id", "name", "'random_header", "Employee.id"], isVisibleDownload: true, dynamicPropertyPathList: [], topRow: 8, bottomRow: 53, parentRowSpace: 10, type: "TABLE_WIDGET", parentColumnSpace: 14.62421875, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "tableData" }, { key: "primaryColumns.id.computedValue" }, { key: "primaryColumns.name.computedValue" }, { key: "primaryColumns.'random_header.computedValue" }, { key: "primaryColumns.Employee.id.computedValue" }, ], leftColumn: 1, primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "id", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.id))}}", }, name: { index: 14, width: 150, id: "name", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "name", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.name))}}", }, "'random_header": { index: 20, width: 150, id: "'random_header", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "'random_header", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.'random_header))}}", }, "Employee.id": { index: 20, width: 150, id: "Employee.id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "Employee.id", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.Employee.id))}}", }, }, delimiter: ",", derivedColumns: {}, rightColumn: 63, textSize: "PARAGRAPH", widgetId: "oclzovhzgx", isVisibleFilters: true, tableData: '{{users.data.concat({ "\'random header": 100})}}', isVisible: true, label: "Data", searchKey: "", version: 1, parentId: "0", totalRecordCount: 0, isLoading: false, isVisibleCompactMode: true, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, email: 261, }, }, ], } as unknown as DSLWidget; const outputDsl = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1080, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 980, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 34, minHeight: 860, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["id", "name", "_random_header", "Employee_id"], isVisibleDownload: true, dynamicPropertyPathList: [], topRow: 8, bottomRow: 53, parentRowSpace: 10, type: "TABLE_WIDGET", parentColumnSpace: 14.62421875, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "tableData" }, { key: "primaryColumns.id.computedValue" }, { key: "primaryColumns.name.computedValue" }, { key: "primaryColumns._random_header.computedValue" }, { key: "primaryColumns.Employee_id.computedValue" }, ], leftColumn: 1, primaryColumns: { id: { index: 0, width: 150, id: "id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "id", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.id))}}", }, name: { index: 14, width: 150, id: "name", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "name", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.name))}}", }, _random_header: { index: 20, width: 150, id: "_random_header", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "'random_header", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._random_header))}}", }, Employee_id: { index: 20, width: 150, id: "Employee_id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "Employee.id", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.Employee_id))}}", }, }, delimiter: ",", derivedColumns: {}, rightColumn: 63, textSize: "PARAGRAPH", widgetId: "oclzovhzgx", isVisibleFilters: true, tableData: '{{users.data.concat({ "\'random header": 100})}}', isVisible: true, label: "Data", searchKey: "", version: 1, parentId: "0", totalRecordCount: 0, isLoading: false, isVisibleCompactMode: true, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, email: 261, }, }, ], }; const badDsl = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1080, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 980, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 34, minHeight: 860, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["Employee.id"], isVisibleDownload: true, dynamicPropertyPathList: [], topRow: 8, bottomRow: 53, parentRowSpace: 10, type: "TABLE_WIDGET", parentColumnSpace: 14.62421875, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "tableData" }, { key: "primaryColumns.Employee.id.computedValue" }, ], leftColumn: 1, primaryColumns: { "Employee.id": { "": { index: 20, width: 150, id: "Employee.id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "Employee.id", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.Employee.id))}}", }, }, }, delimiter: ",", derivedColumns: {}, rightColumn: 63, textSize: "PARAGRAPH", widgetId: "oclzovhzgx", isVisibleFilters: true, tableData: '{{users.data.concat({ "\'random header": 100})}}', isVisible: true, label: "Data", searchKey: "", version: 1, parentId: "0", totalRecordCount: 0, isLoading: false, isVisibleCompactMode: true, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, email: 261, }, }, ], } as unknown as DSLWidget; const fixedDsl = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1080, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 980, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 34, minHeight: 860, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, children: [ { widgetName: "Table1", defaultPageSize: 0, columnOrder: ["Employee_id"], isVisibleDownload: true, dynamicPropertyPathList: [], topRow: 8, bottomRow: 53, parentRowSpace: 10, type: "TABLE_WIDGET", parentColumnSpace: 14.62421875, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "tableData" }, { key: "primaryColumns.Employee_id.computedValue" }, ], leftColumn: 1, primaryColumns: { Employee_id: { index: 20, width: 150, id: "Employee_id", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "Employee.id", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.Employee_id))}}", }, }, delimiter: ",", derivedColumns: {}, rightColumn: 63, textSize: "PARAGRAPH", widgetId: "oclzovhzgx", isVisibleFilters: true, tableData: '{{users.data.concat({ "\'random header": 100})}}', isVisible: true, label: "Data", searchKey: "", version: 1, parentId: "0", totalRecordCount: 0, isLoading: false, isVisibleCompactMode: true, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, email: 261, }, }, ], }; const newDsl = migrateTableSanitizeColumnKeys(inputDsl); const correctedDsl = migrateTableSanitizeColumnKeys(badDsl); expect(newDsl).toStrictEqual(outputDsl); expect(correctedDsl).toStrictEqual(fixedDsl); }); }); describe("Table Widget selectedRow bindings update", () => { it("To test selectedRow bindings are updated for primaryColumns and derivedColumns", () => { const inputDsl: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 540, containerStyle: "none", snapRows: 129, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 36, minHeight: 550, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, renderMode: "CANVAS", isLoading: false, children: [ { widgetName: "Table1", defaultPageSize: 0, isVisibleDownload: true, dynamicPropertyPathList: [], topRow: 8, bottomRow: 36, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", parentColumnSpace: 17.28125, dynamicTriggerPathList: [{ key: "primaryColumns.action.onClick" }], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue" }, { key: "primaryColumns.task.computedValue" }, { key: "primaryColumns.status.computedValue" }, { key: "primaryColumns.action.computedValue" }, ], leftColumn: 6, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{showAlert(Table1.selectedRow.task,'info')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", }, customColumn1: { index: 4, width: 150, id: "customColumn1", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: true, label: "Delete", onClick: "{{showAlert('Hello')}}", computedValue: "", }, }, delimiter: ",", derivedColumns: {}, rightColumn: 36, textSize: "PARAGRAPH", widgetId: "yd68qpgb0b", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "" }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", version: 1, totalRecordsCount: 0, parentId: "0", isLoading: false, horizontalAlignment: "LEFT", renderMode: "CANVAS", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75 }, }, ], }; const newDsl = migrateTableWidgetSelectedRowBindings(inputDsl); const outputDsl: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 540, containerStyle: "none", snapRows: 129, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 36, minHeight: 550, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, renderMode: "CANVAS", isLoading: false, children: [ { widgetName: "Table1", defaultPageSize: 0, isVisibleDownload: true, dynamicPropertyPathList: [], topRow: 8, bottomRow: 36, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", parentColumnSpace: 17.28125, dynamicTriggerPathList: [{ key: "primaryColumns.action.onClick" }], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue" }, { key: "primaryColumns.task.computedValue" }, { key: "primaryColumns.status.computedValue" }, { key: "primaryColumns.action.computedValue" }, ], leftColumn: 6, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{showAlert(currentRow.task,'info')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", }, customColumn1: { index: 4, width: 150, id: "customColumn1", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: true, label: "Delete", onClick: "{{showAlert('Hello')}}", computedValue: "", }, }, delimiter: ",", derivedColumns: {}, rightColumn: 36, textSize: "PARAGRAPH", widgetId: "yd68qpgb0b", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "" }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", version: 1, totalRecordsCount: 0, parentId: "0", isLoading: false, horizontalAlignment: "LEFT", renderMode: "CANVAS", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75 }, }, ], }; expect(newDsl).toStrictEqual(outputDsl); }); }); describe("Table Widget numeric column name to string update", () => { it("to test numeric column name converted to string and rest column configuration remains same", () => { const inputDsl: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 816, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 5016, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 50, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, parentId: "", renderMode: "CANVAS", isLoading: false, children: [ { widgetName: "Table1", parentColumnSpace: 74, defaultPageSize: 0, columnOrder: [ "1", "2", "_user_", "_client_", "rowIndex", "customColumn1", "customColumn2", ], isVisibleDownload: true, dynamicPropertyPathList: [], displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 1, bottomRow: 29, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, isLoading: false, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "tableData", }, { key: "primaryColumns.1.computedValue", }, { key: "primaryColumns.2.computedValue", }, { key: "primaryColumns._user_.computedValue", }, { key: "primaryColumns._client_.computedValue", }, { key: "primaryColumns.rowIndex.computedValue", }, { key: "derivedColumns.customColumn1.computedValue", }, { key: "primaryColumns.customColumn1.computedValue", }, { key: "derivedColumns.customColumn2.computedValue", }, { key: "primaryColumns.customColumn2.computedValue", }, ], leftColumn: 0, primaryColumns: { "1": { index: 0, width: 150, id: "1", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "ONE", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.1))}}", }, "2": { index: 1, width: 150, id: "2", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "TWO", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.2))}}", }, _user_: { index: 2, width: 150, id: "_user_", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "USER", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._user_))}}", }, _client_: { index: 3, width: 150, id: "_client_", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "CLIENT", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._client_))}}", }, rowIndex: { index: 4, width: 150, id: "rowIndex", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "rowIndex", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex))}}", }, customColumn1: { index: 5, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "Custom Column 1", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn2: { index: 6, width: 150, id: "customColumn2", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "Custom Label", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn2))}}", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "d0akgsw2t4", derivedColumns: { customColumn1: { index: 5, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "Custom Column 1", computedValue: '{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex + " CC1"))}}', buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn2: { index: 6, width: 150, id: "customColumn2", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "Custom Label", computedValue: '{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex + " CC1"))}}', buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 34, textSize: "PARAGRAPH", widgetId: "v3kdn1uyjb", isVisibleFilters: true, tableData: "{{Api2.data}}", isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, }, ], }; // using cloneDeep, create new reference of inputDsl // otherwise migration function will modify inputDsl too const newDsl = migrateTableWidgetNumericColumnName(cloneDeep(inputDsl)); const outputDsl: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 816, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 5016, containerStyle: "none", snapRows: 125, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 50, minHeight: 1292, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, parentId: "", renderMode: "CANVAS", isLoading: false, children: [ { widgetName: "Table1", parentColumnSpace: 74, defaultPageSize: 0, columnOrder: [ "_1", "_2", "_user_", "_client_", "rowIndex", "customColumn1", "customColumn2", ], isVisibleDownload: true, dynamicPropertyPathList: [], displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 1, bottomRow: 29, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, animateLoading: true, isLoading: false, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "tableData", }, { key: "primaryColumns._1.computedValue", }, { key: "primaryColumns._2.computedValue", }, { key: "primaryColumns._user_.computedValue", }, { key: "primaryColumns._client_.computedValue", }, { key: "primaryColumns.rowIndex.computedValue", }, { key: "derivedColumns.customColumn1.computedValue", }, { key: "primaryColumns.customColumn1.computedValue", }, { key: "derivedColumns.customColumn2.computedValue", }, { key: "primaryColumns.customColumn2.computedValue", }, ], leftColumn: 0, primaryColumns: { _1: { index: 0, width: 150, id: "_1", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "ONE", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._1))}}", }, _2: { index: 1, width: 150, id: "_2", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "TWO", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._2))}}", }, _user_: { index: 2, width: 150, id: "_user_", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "USER", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._user_))}}", }, _client_: { index: 3, width: 150, id: "_client_", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "CLIENT", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow._client_))}}", }, rowIndex: { index: 4, width: 150, id: "rowIndex", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: false, label: "rowIndex", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex))}}", }, customColumn1: { index: 5, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "Custom Column 1", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn1))}}", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn2: { index: 6, width: 150, id: "customColumn2", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "Custom Label", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.customColumn2))}}", buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, delimiter: ",", key: "d0akgsw2t4", derivedColumns: { customColumn1: { index: 5, width: 150, id: "customColumn1", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "Custom Column 1", computedValue: '{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex + " CC1"))}}', buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, customColumn2: { index: 6, width: 150, id: "customColumn2", columnType: "text", enableFilter: true, enableSort: true, isVisible: true, isDisabled: false, isCellVisible: true, isDerived: true, label: "Custom Label", computedValue: '{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.rowIndex + " CC1"))}}', buttonStyle: "rgb(3, 179, 101)", buttonLabelColor: "#FFFFFF", buttonColor: "#03B365", menuColor: "#03B365", labelColor: "#FFFFFF", }, }, rightColumn: 34, textSize: "PARAGRAPH", widgetId: "v3kdn1uyjb", isVisibleFilters: true, tableData: "{{Api2.data}}", isVisible: true, label: "Data", searchKey: "", enableClientSideSearch: true, version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, }, ], }; expect(newDsl).toStrictEqual(outputDsl); }); }); const oldBindingPrefix = `{{ ( (editedValue, currentRow, currentIndex) => ( `; const newBindingPrefix = `{{ ( (editedValue, currentRow, currentIndex, isNewRow) => ( `; const oldBindingSuffix = (tableId: string, columnName: string) => ` )) ( ${tableId}.columnEditableCellValue.${columnName} || "", ${tableId}.processedTableData[${tableId}.editableCell.index] || Object.keys(${tableId}.processedTableData[0]) .filter(key => ["__originalIndex__", "__primaryKey__"].indexOf(key) === -1) .reduce((prev, curr) => { prev[curr] = ""; return prev; }, {}), ${tableId}.editableCell.index) }} `; const newBindingSuffix = (tableId: string, columnName: string) => { return ` )) ( (${tableId}.isAddRowInProgress ? ${tableId}.newRow.${columnName} : ${tableId}.columnEditableCellValue.${columnName}) || "", ${tableId}.isAddRowInProgress ? ${tableId}.newRow : (${tableId}.processedTableData[${tableId}.editableCell.index] || Object.keys(${tableId}.processedTableData[0]) .filter(key => ["__originalIndex__", "__primaryKey__"].indexOf(key) === -1) .reduce((prev, curr) => { prev[curr] = ""; return prev; }, {})), ${tableId}.isAddRowInProgress ? -1 : ${tableId}.editableCell.index, ${tableId}.isAddRowInProgress ) }} `; }; describe("migrateTableWidgetV2ValidationBinding", () => { const binding = "true"; it("should test that binding of isColumnEditableCellValid is getting updated", () => { expect( migrateTableWidgetV2ValidationBinding({ children: [ { widgetName: "Table", type: "TABLE_WIDGET_V2", primaryColumns: { step: { validation: { isColumnEditableCellValid: `${oldBindingPrefix}${binding}${oldBindingSuffix( "Table", "step", )}`, }, }, }, }, ], } as any as DSLWidget), ).toEqual({ children: [ { widgetName: "Table", type: "TABLE_WIDGET_V2", primaryColumns: { step: { validation: { isColumnEditableCellValid: `${newBindingPrefix}${binding}${newBindingSuffix( "Table", "step", )}`, }, }, }, }, ], }); }); }); describe("migrateTableWidgetV2SelectOption", () => { it("should test that binding of selectOption is getting updated", () => { expect( migrateTableWidgetV2SelectOption({ children: [ { widgetName: "Table", type: "TABLE_WIDGET_V2", primaryColumns: { step: { columnType: "select", selectOptions: "[{label: 1, value: 2}]", }, task: { columnType: "select", selectOptions: "{{[{label: 1, value: 2}]}}", }, status: { columnType: "text", selectOptions: "{{[{label: 1, value: 2}]}}", }, }, }, ], } as any as DSLWidget), ).toEqual({ children: [ { widgetName: "Table", type: "TABLE_WIDGET_V2", primaryColumns: { step: { columnType: "select", selectOptions: "[{label: 1, value: 2}]", }, task: { columnType: "select", selectOptions: "{{Table.processedTableData.map((currentRow, currentIndex) => ( [{label: 1, value: 2}]))}}", }, status: { columnType: "text", selectOptions: "{{[{label: 1, value: 2}]}}", }, }, }, ], }); }); }); describe("migrateTableWidgetTableDataJsMode", () => { it("should test that tableData js mode is enabled", () => { expect( migrateTableWidgetTableDataJsMode({ children: [ { widgetName: "Table", type: "TABLE_WIDGET_V2", primaryColumns: { step: { columnType: "select", selectOptions: "[{label: 1, value: 2}]", }, task: { columnType: "select", selectOptions: "{{[{label: 1, value: 2}]}}", }, status: { columnType: "text", selectOptions: "{{[{label: 1, value: 2}]}}", }, }, }, { widgetName: "Table1", type: "TABLE_WIDGET_V2", primaryColumns: { step: { columnType: "select", selectOptions: "[{label: 1, value: 2}]", }, task: { columnType: "select", selectOptions: "{{[{label: 1, value: 2}]}}", }, status: { columnType: "text", selectOptions: "{{[{label: 1, value: 2}]}}", }, }, dynamicPropertyPathList: [{ key: "test" }], }, { widgetName: "Text", type: "TEXT_WIDGET", dynamicPropertyPathList: [{ key: "test" }], }, ], } as any as DSLWidget), ).toEqual({ children: [ { widgetName: "Table", type: "TABLE_WIDGET_V2", primaryColumns: { step: { columnType: "select", selectOptions: "[{label: 1, value: 2}]", }, task: { columnType: "select", selectOptions: "{{[{label: 1, value: 2}]}}", }, status: { columnType: "text", selectOptions: "{{[{label: 1, value: 2}]}}", }, }, dynamicPropertyPathList: [{ key: "tableData" }], }, { widgetName: "Table1", type: "TABLE_WIDGET_V2", primaryColumns: { step: { columnType: "select", selectOptions: "[{label: 1, value: 2}]", }, task: { columnType: "select", selectOptions: "{{[{label: 1, value: 2}]}}", }, status: { columnType: "text", selectOptions: "{{[{label: 1, value: 2}]}}", }, }, dynamicPropertyPathList: [{ key: "test" }, { key: "tableData" }], }, { widgetName: "Text", type: "TEXT_WIDGET", dynamicPropertyPathList: [{ key: "test" }], }, ], }); }); });
1,501
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/TextWidget.test.ts
import { migrateTextStyleFromTextWidget, migrateScrollTruncateProperties, } from "utils/migrations/TextWidget"; import { FontStyleTypes, TextSizes } from "constants/WidgetConstants"; import type { DSLWidget } from "WidgetProvider/constants"; import { OverflowTypes } from "widgets/TextWidget/constants"; const inputDsl1: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textStyle: "LABEL", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], renderMode: "CANVAS", }, ], }; const inputDsl2: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textStyle: "HEADING", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], renderMode: "CANVAS", }, ], }; const inputDsl3: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textStyle: "BODY", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], renderMode: "CANVAS", }, ], }; const outputDsl1: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.PARAGRAPH, fontStyle: FontStyleTypes.BOLD, renderMode: "CANVAS", }, ], }; const outputDsl2: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.HEADING1, fontStyle: FontStyleTypes.BOLD, renderMode: "CANVAS", }, ], }; const outputDsl3: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.PARAGRAPH, renderMode: "CANVAS", }, ], }; describe("Text Widget Property Pane Upgrade", () => { it("To test text widget textStyle property is migrated", () => { const newDsl = migrateTextStyleFromTextWidget(inputDsl1); expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl1)); }); it("To test text widget textStyle property is migrated", () => { const newDsl = migrateTextStyleFromTextWidget(inputDsl2); expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl2)); }); it("To test text widget textStyle property is migrated", () => { const newDsl = migrateTextStyleFromTextWidget(inputDsl3); expect(JSON.stringify(newDsl) === JSON.stringify(outputDsl3)); }); }); const inputDsl4: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.PARAGRAPH, fontStyle: FontStyleTypes.BOLD, renderMode: "CANVAS", shouldScroll: true, shouldTruncate: false, }, ], }; const outputDsl4: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.PARAGRAPH, fontStyle: FontStyleTypes.BOLD, renderMode: "CANVAS", overflow: OverflowTypes.SCROLL, }, ], }; const inputDsl5: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.PARAGRAPH, fontStyle: FontStyleTypes.BOLD, renderMode: "CANVAS", shouldScroll: true, shouldTruncate: true, }, ], }; const outputDsl5: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.PARAGRAPH, fontStyle: FontStyleTypes.BOLD, renderMode: "CANVAS", overflow: OverflowTypes.TRUNCATE, }, ], }; const inputDsl6: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.PARAGRAPH, fontStyle: FontStyleTypes.BOLD, renderMode: "CANVAS", shouldScroll: false, shouldTruncate: false, }, ], }; const outputDsl6: DSLWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1280, containerStyle: "none", snapRows: 33, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 15, minHeight: 1292, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, isLoading: false, parentId: "", renderMode: "CANVAS", children: [ { isVisible: true, text: "Label", textAlign: "LEFT", widgetName: "Text1", version: 1, type: "TEXT_WIDGET", isLoading: false, parentColumnSpace: 67.375, parentRowSpace: 40, leftColumn: 3, rightColumn: 7, topRow: 1, bottomRow: 2, parentId: "0", widgetId: "yf8bhokz7d", dynamicBindingPathList: [], fontSize: TextSizes.PARAGRAPH, fontStyle: FontStyleTypes.BOLD, renderMode: "CANVAS", overflow: OverflowTypes.NONE, }, ], }; describe("Text Widget Scroll and Truncate Property migrate", () => { it("Overflow value should be SCROLL instead of shouldScroll true", () => { const newDsl = migrateScrollTruncateProperties(inputDsl4); expect(newDsl).toEqual(outputDsl4); }); it("Overflow value should be TRUNCATE instead of shouldTruncate true", () => { const newDsl = migrateScrollTruncateProperties(inputDsl5); expect(newDsl).toEqual(outputDsl5); }); it("Overflow value should be NONE in case of shouldScroll and shouldTruncate are false", () => { const newDsl = migrateScrollTruncateProperties(inputDsl6); expect(newDsl).toEqual(outputDsl6); }); });
1,503
0
petrpan-code/appsmithorg/appsmith/app/client/src/utils
petrpan-code/appsmithorg/appsmith/app/client/src/utils/migrations/ThemingMigration.test.ts
import { klona } from "klona"; import type { DSLWidget } from "WidgetProvider/constants"; import { migrateChildStylesheetFromDynamicBindingPathList } from "./ThemingMigrations"; const inputDSL1 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1040, containerStyle: "none", snapRows: 124, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 70, minHeight: 1250, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { schema: { __root_schema__: { children: { name: { children: {}, dataType: "string", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.name))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: "Text Input", sourceData: "John", isCustomField: false, accessor: "name", identifier: "name", position: 0, originalIdentifier: "name", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Name", }, date_of_birth: { children: {}, dataType: "string", defaultValue: '{{((sourceData, formData, fieldState) => (moment(sourceData.date_of_birth, "DD/MM/YYYY").format("YYYY-MM-DDTHH:mm:ss.sssZ")))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}', fieldType: "Datepicker", sourceData: "20/02/1990", isCustomField: false, accessor: "date_of_birth", identifier: "date_of_birth", position: 1, originalIdentifier: "date_of_birth", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", closeOnSelection: false, convertToISO: false, dateFormat: "DD/MM/YYYY", isDisabled: false, isRequired: false, isVisible: true, label: "Date Of Birth", maxDate: "2121-12-31T18:29:00.000Z", minDate: "1920-12-31T18:30:00.000Z", shortcuts: false, timePrecision: "minute", labelTextSize: "0.875rem", }, employee_id: { children: {}, dataType: "number", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.employee_id))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: "Number Input", sourceData: 1001, isCustomField: false, accessor: "employee_id", identifier: "employee_id", position: 2, originalIdentifier: "employee_id", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Employee Id", }, childStylesheet: { children: {}, dataType: "string", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.childStylesheet))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: "Text Input", sourceData: "asd", isCustomField: false, accessor: "childStylesheet", identifier: "childStylesheet", position: 3, originalIdentifier: "childStylesheet", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Child Stylesheet", }, }, dataType: "object", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: "Object", sourceData: { name: "John", date_of_birth: "20/02/1990", employee_id: 1001, childStylesheet: "asd", }, isCustomField: false, accessor: "__root_schema__", identifier: "__root_schema__", position: -1, originalIdentifier: "__root_schema__", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", cellBorderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", cellBoxShadow: "none", isDisabled: false, isRequired: false, isVisible: true, labelTextSize: "0.875rem", label: "", }, }, boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", borderColor: "#E0DEDE", widgetName: "JSONForm1", submitButtonStyles: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", buttonVariant: "PRIMARY", }, dynamicPropertyPathList: [ { key: "schema.__root_schema__.children.date_of_birth.defaultValue", }, ], displayName: "JSON Form", iconSVG: "/static/media/icon.5b428de12db9ad6a591955ead07f86e9.svg", topRow: 0, bottomRow: 50, fieldLimitExceeded: false, parentRowSpace: 10, title: "Form", type: "JSON_FORM_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 42.5625, dynamicTriggerPathList: [], leftColumn: 1, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, { key: "submitButtonStyles.buttonColor", }, { key: "submitButtonStyles.borderRadius", }, { key: "resetButtonStyles.buttonColor", }, { key: "resetButtonStyles.borderRadius", }, { key: "childStylesheet.ARRAY.accentColor", }, { key: "childStylesheet.ARRAY.borderRadius", }, { key: "childStylesheet.ARRAY.cellBorderRadius", }, { key: "childStylesheet.OBJECT.borderRadius", }, { key: "childStylesheet.OBJECT.cellBorderRadius", }, { key: "childStylesheet.CHECKBOX.accentColor", }, { key: "childStylesheet.CHECKBOX.borderRadius", }, { key: "childStylesheet.CURRENCY_INPUT.accentColor", }, { key: "childStylesheet.CURRENCY_INPUT.borderRadius", }, { key: "childStylesheet.DATEPICKER.accentColor", }, { key: "childStylesheet.DATEPICKER.borderRadius", }, { key: "childStylesheet.EMAIL_INPUT.accentColor", }, { key: "childStylesheet.EMAIL_INPUT.borderRadius", }, { key: "childStylesheet.MULTISELECT.accentColor", }, { key: "childStylesheet.MULTISELECT.borderRadius", }, { key: "childStylesheet.MULTILINE_TEXT_INPUT.accentColor", }, { key: "childStylesheet.MULTILINE_TEXT_INPUT.borderRadius", }, { key: "childStylesheet.NUMBER_INPUT.accentColor", }, { key: "childStylesheet.NUMBER_INPUT.borderRadius", }, { key: "childStylesheet.PASSWORD_INPUT.accentColor", }, { key: "childStylesheet.PASSWORD_INPUT.borderRadius", }, { key: "childStylesheet.PHONE_NUMBER_INPUT.accentColor", }, { key: "childStylesheet.PHONE_NUMBER_INPUT.borderRadius", }, { key: "childStylesheet.RADIO_GROUP.accentColor", }, { key: "childStylesheet.SELECT.accentColor", }, { key: "childStylesheet.SELECT.borderRadius", }, { key: "childStylesheet.SWITCH.accentColor", }, { key: "childStylesheet.TEXT_INPUT.accentColor", }, { key: "childStylesheet.TEXT_INPUT.borderRadius", }, { key: "schema.__root_schema__.children.name.defaultValue", }, { key: "schema.__root_schema__.children.name.accentColor", }, { key: "schema.__root_schema__.children.name.borderRadius", }, { key: "schema.__root_schema__.children.date_of_birth.defaultValue", }, { key: "schema.__root_schema__.children.date_of_birth.accentColor", }, { key: "schema.__root_schema__.children.date_of_birth.borderRadius", }, { key: "schema.__root_schema__.children.employee_id.defaultValue", }, { key: "schema.__root_schema__.children.employee_id.accentColor", }, { key: "schema.__root_schema__.children.employee_id.borderRadius", }, { key: "schema.__root_schema__.defaultValue", }, { key: "schema.__root_schema__.borderRadius", }, { key: "schema.__root_schema__.cellBorderRadius", }, { key: "schema.__root_schema__.children.childStylesheet.defaultValue", }, { key: "schema.__root_schema__.children.childStylesheet.accentColor", }, { key: "schema.__root_schema__.children.childStylesheet.borderRadius", }, ], borderWidth: "1", sourceData: '{\n "name": "John",\n "date_of_birth": "20/02/1990",\n "employee_id": 1001,\n\t"childStylesheet":"asd"\n}', showReset: true, resetButtonLabel: "Reset", key: "4r1dire8mf", backgroundColor: "#fff", isDeprecated: false, rightColumn: 26, dynamicHeight: "FIXED", autoGenerateForm: true, widgetId: "136kliil8g", resetButtonStyles: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", buttonVariant: "SECONDARY", }, isVisible: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, scrollContents: true, fixedFooter: true, submitButtonLabel: "Submit", childStylesheet: { ARRAY: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", cellBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", cellBoxShadow: "none", }, OBJECT: { borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", cellBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", cellBoxShadow: "none", }, CHECKBOX: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, CURRENCY_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, DATEPICKER: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, EMAIL_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, MULTISELECT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, MULTILINE_TEXT_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, NUMBER_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, PASSWORD_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, PHONE_NUMBER_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, RADIO_GROUP: { accentColor: "{{appsmith.theme.colors.primaryColor}}", boxShadow: "none", }, SELECT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, SWITCH: { accentColor: "{{appsmith.theme.colors.primaryColor}}", boxShadow: "none", }, TEXT_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, }, disabledWhenInvalid: true, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", maxDynamicHeight: 9000, minDynamicHeight: 4, }, { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", borderColor: "#E0DEDE", isVisibleDownload: true, iconSVG: "/static/media/icon.db8a9cbd2acd22a31ea91cc37ea2a46c.svg", topRow: 2, isSortable: true, type: "TABLE_WIDGET_V2", inlineEditingSaveOption: "ROW_LEVEL", animateLoading: true, dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, { key: "primaryColumns.action.buttonColor", }, { key: "primaryColumns.action.borderRadius", }, { key: "primaryColumns.action.boxShadow", }, { key: "accentColor", }, { key: "borderRadius", }, { key: "boxShadow", }, { key: "childStylesheet.button.buttonColor", }, { key: "childStylesheet.button.borderRadius", }, { key: "childStylesheet.menuButton.menuColor", }, { key: "childStylesheet.menuButton.borderRadius", }, { key: "childStylesheet.iconButton.buttonColor", }, { key: "childStylesheet.iconButton.borderRadius", }, { key: "childStylesheet.editActions.saveButtonColor", }, { key: "childStylesheet.editActions.saveBorderRadius", }, { key: "childStylesheet.editActions.discardButtonColor", }, { key: "childStylesheet.editActions.discardBorderRadius", }, ], leftColumn: 27, delimiter: ",", defaultSelectedRowIndex: 0, accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisibleFilters: true, isVisible: true, enableClientSideSearch: true, version: 1, totalRecordsCount: 0, isLoading: false, childStylesheet: { button: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, menuButton: { menuColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, iconButton: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, editActions: { saveButtonColor: "{{appsmith.theme.colors.primaryColor}}", saveBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", discardButtonColor: "{{appsmith.theme.colors.primaryColor}}", discardBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, }, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", defaultSelectedRowIndices: [0], widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action"], dynamicPropertyPathList: [], displayName: "Table", bottomRow: 30, columnWidthMap: { task: 245, step: 62, status: 75, }, parentRowSpace: 10, hideCard: false, parentColumnSpace: 42.5625, borderWidth: "1", primaryColumns: { step: { index: 0, width: 150, id: "step", originalId: "step", alias: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "step", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["step"]))}}', validation: {}, labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", originalId: "task", alias: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "task", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["task"]))}}', validation: {}, labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", originalId: "status", alias: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "status", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["status"]))}}', validation: {}, labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", originalId: "action", alias: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["action"]))}}', validation: {}, labelColor: "#FFFFFF", buttonColor: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.colors.primaryColor))}}", borderRadius: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.borderRadius.appBorderRadius))}}", boxShadow: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( 'none'))}}", }, }, key: "xi3zw81eiq", isDeprecated: false, rightColumn: 61, textSize: "0.875rem", widgetId: "6w4nk55npx", tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], label: "Data", searchKey: "", parentId: "0", renderMode: "CANVAS", horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", }, { boxShadow: "none", widgetName: "ButtonGroup1", isCanvas: false, displayName: "Button Group", iconSVG: "/static/media/icon.d6773218cfb61dcfa5f460d43371e30d.svg", searchTags: ["click", "submit"], topRow: 57, bottomRow: 61, parentRowSpace: 10, groupButtons: { groupButton1: { label: "Favorite", iconName: "heart", id: "groupButton1", widgetId: "", buttonType: "SIMPLE", placement: "CENTER", isVisible: true, isDisabled: false, index: 0, menuItems: {}, buttonColor: "{{appsmith.theme.colors.primaryColor}}", }, groupButton2: { label: "Add", iconName: "add", id: "groupButton2", buttonType: "SIMPLE", placement: "CENTER", widgetId: "", isVisible: true, isDisabled: false, index: 1, menuItems: {}, buttonColor: "{{appsmith.theme.colors.primaryColor}}", }, groupButton3: { label: "More", iconName: "more", id: "groupButton3", buttonType: "MENU", placement: "CENTER", widgetId: "", isVisible: true, isDisabled: false, index: 2, menuItems: { menuItem1: { label: "First Option", backgroundColor: "#FFFFFF", id: "menuItem1", widgetId: "", onClick: "", isVisible: true, isDisabled: false, index: 0, }, menuItem2: { label: "Second Option", backgroundColor: "#FFFFFF", id: "menuItem2", widgetId: "", onClick: "", isVisible: true, isDisabled: false, index: 1, }, menuItem3: { label: "Delete", iconName: "trash", iconColor: "#FFFFFF", iconAlign: "right", textColor: "#FFFFFF", backgroundColor: "#DD4B34", id: "menuItem3", widgetId: "", onClick: "", isVisible: true, isDisabled: false, index: 2, }, }, buttonColor: "{{appsmith.theme.colors.primaryColor}}", }, }, type: "BUTTON_GROUP_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 42.5625, leftColumn: 3, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "childStylesheet.button.buttonColor", }, { key: "groupButtons.groupButton1.buttonColor", }, { key: "groupButtons.groupButton2.buttonColor", }, { key: "groupButtons.groupButton3.buttonColor", }, ], key: "kahzuua49o", orientation: "horizontal", isDeprecated: false, rightColumn: 27, widgetId: "tt1sptkg2z", isVisible: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, childStylesheet: { button: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", }, }, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", buttonVariant: "PRIMARY", }, { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Container1", borderColor: "#E0DEDE", isCanvas: true, displayName: "Container", iconSVG: "/static/media/icon.1977dca3370505e2db3a8e44cfd54907.svg", searchTags: ["div", "parent", "group"], topRow: 44, bottomRow: 96, parentRowSpace: 10, type: "CONTAINER_WIDGET", hideCard: false, shouldScrollContents: true, animateLoading: true, parentColumnSpace: 42.5625, leftColumn: 27, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, ], children: [ { widgetName: "Canvas1", displayName: "Canvas", topRow: 0, bottomRow: 520, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: false, hideCard: true, minHeight: 520, parentColumnSpace: 1, leftColumn: 0, dynamicBindingPathList: [], children: [ { schema: { __root_schema__: { children: { name: { children: {}, dataType: "string", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.name))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", fieldType: "Text Input", sourceData: "John", isCustomField: false, accessor: "name", identifier: "name", position: 0, originalIdentifier: "name", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Name", }, date_of_birth: { children: {}, dataType: "string", defaultValue: '{{((sourceData, formData, fieldState) => (moment(sourceData.date_of_birth, "DD/MM/YYYY").format("YYYY-MM-DDTHH:mm:ss.sssZ")))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}', fieldType: "Datepicker", sourceData: "20/02/1990", isCustomField: false, accessor: "date_of_birth", identifier: "date_of_birth", position: 1, originalIdentifier: "date_of_birth", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", boxShadow: "none", closeOnSelection: false, convertToISO: false, dateFormat: "DD/MM/YYYY", isDisabled: false, isRequired: false, isVisible: true, label: "Date Of Birth", maxDate: "2121-12-31T18:29:00.000Z", minDate: "1920-12-31T18:30:00.000Z", shortcuts: false, timePrecision: "minute", labelTextSize: "0.875rem", }, employee_id: { children: {}, dataType: "number", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.employee_id))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", fieldType: "Number Input", sourceData: 1001, isCustomField: false, accessor: "employee_id", identifier: "employee_id", position: 2, originalIdentifier: "employee_id", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Employee Id", }, }, dataType: "object", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", fieldType: "Object", sourceData: { name: "John", date_of_birth: "20/02/1990", employee_id: 1001, }, isCustomField: false, accessor: "__root_schema__", identifier: "__root_schema__", position: -1, originalIdentifier: "__root_schema__", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", boxShadow: "none", cellBorderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", cellBoxShadow: "none", isDisabled: false, isRequired: false, isVisible: true, labelTextSize: "0.875rem", label: "", }, }, boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", borderColor: "#E0DEDE", widgetName: "JSONForm2", submitButtonStyles: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", buttonVariant: "PRIMARY", }, dynamicPropertyPathList: [ { key: "schema.__root_schema__.children.date_of_birth.defaultValue", }, ], displayName: "JSON Form", iconSVG: "/static/media/icon.5b428de12db9ad6a591955ead07f86e9.svg", topRow: 0, bottomRow: 50, fieldLimitExceeded: false, parentRowSpace: 10, title: "Form", type: "JSON_FORM_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 15.6484375, dynamicTriggerPathList: [], leftColumn: 13, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, { key: "submitButtonStyles.buttonColor", }, { key: "submitButtonStyles.borderRadius", }, { key: "resetButtonStyles.buttonColor", }, { key: "resetButtonStyles.borderRadius", }, { key: "childStylesheet.ARRAY.accentColor", }, { key: "childStylesheet.ARRAY.borderRadius", }, { key: "childStylesheet.ARRAY.cellBorderRadius", }, { key: "childStylesheet.OBJECT.borderRadius", }, { key: "childStylesheet.OBJECT.cellBorderRadius", }, { key: "childStylesheet.CHECKBOX.accentColor", }, { key: "childStylesheet.CHECKBOX.borderRadius", }, { key: "childStylesheet.CURRENCY_INPUT.accentColor", }, { key: "childStylesheet.CURRENCY_INPUT.borderRadius", }, { key: "childStylesheet.DATEPICKER.accentColor", }, { key: "childStylesheet.DATEPICKER.borderRadius", }, { key: "childStylesheet.EMAIL_INPUT.accentColor", }, { key: "childStylesheet.EMAIL_INPUT.borderRadius", }, { key: "childStylesheet.MULTISELECT.accentColor", }, { key: "childStylesheet.MULTISELECT.borderRadius", }, { key: "childStylesheet.MULTILINE_TEXT_INPUT.accentColor", }, { key: "childStylesheet.MULTILINE_TEXT_INPUT.borderRadius", }, { key: "childStylesheet.NUMBER_INPUT.accentColor", }, { key: "childStylesheet.NUMBER_INPUT.borderRadius", }, { key: "childStylesheet.PASSWORD_INPUT.accentColor", }, { key: "childStylesheet.PASSWORD_INPUT.borderRadius", }, { key: "childStylesheet.PHONE_NUMBER_INPUT.accentColor", }, { key: "childStylesheet.PHONE_NUMBER_INPUT.borderRadius", }, { key: "childStylesheet.RADIO_GROUP.accentColor", }, { key: "childStylesheet.SELECT.accentColor", }, { key: "childStylesheet.SELECT.borderRadius", }, { key: "childStylesheet.SWITCH.accentColor", }, { key: "childStylesheet.TEXT_INPUT.accentColor", }, { key: "childStylesheet.TEXT_INPUT.borderRadius", }, { key: "schema.__root_schema__.children.name.defaultValue", }, { key: "schema.__root_schema__.children.name.accentColor", }, { key: "schema.__root_schema__.children.name.borderRadius", }, { key: "schema.__root_schema__.children.date_of_birth.defaultValue", }, { key: "schema.__root_schema__.children.date_of_birth.accentColor", }, { key: "schema.__root_schema__.children.date_of_birth.borderRadius", }, { key: "schema.__root_schema__.children.employee_id.defaultValue", }, { key: "schema.__root_schema__.children.employee_id.accentColor", }, { key: "schema.__root_schema__.children.employee_id.borderRadius", }, { key: "schema.__root_schema__.defaultValue", }, { key: "schema.__root_schema__.borderRadius", }, { key: "schema.__root_schema__.cellBorderRadius", }, ], borderWidth: "1", sourceData: { name: "John", date_of_birth: "20/02/1990", employee_id: 1001, }, showReset: true, resetButtonLabel: "Reset", key: "4r1dire8mf", backgroundColor: "#fff", isDeprecated: false, rightColumn: 38, dynamicHeight: "FIXED", autoGenerateForm: true, widgetId: "3m7vsrp7a8", resetButtonStyles: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", buttonVariant: "SECONDARY", }, isVisible: true, version: 1, parentId: "q71uafkl98", renderMode: "CANVAS", isLoading: false, scrollContents: true, fixedFooter: true, submitButtonLabel: "Submit", childStylesheet: { ARRAY: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", cellBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", cellBoxShadow: "none", }, OBJECT: { borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", cellBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", cellBoxShadow: "none", }, CHECKBOX: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, CURRENCY_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, DATEPICKER: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, EMAIL_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, MULTISELECT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, MULTILINE_TEXT_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, NUMBER_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, PASSWORD_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, PHONE_NUMBER_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, RADIO_GROUP: { accentColor: "{{appsmith.theme.colors.primaryColor}}", boxShadow: "none", }, SELECT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, SWITCH: { accentColor: "{{appsmith.theme.colors.primaryColor}}", boxShadow: "none", }, TEXT_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, }, disabledWhenInvalid: true, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", maxDynamicHeight: 9000, minDynamicHeight: 4, }, ], key: "rkukmmul97", isDeprecated: false, rightColumn: 1021.5, detachFromLayout: true, widgetId: "q71uafkl98", containerStyle: "none", isVisible: true, version: 1, parentId: "08plhw35jc", renderMode: "CANVAS", isLoading: false, }, ], borderWidth: "1", key: "c5ggn97bsx", backgroundColor: "#FFFFFF", isDeprecated: false, rightColumn: 51, dynamicHeight: "AUTO_HEIGHT", widgetId: "08plhw35jc", containerStyle: "card", isVisible: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, originalTopRow: 44, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", maxDynamicHeight: 9000, originalBottomRow: 54, minDynamicHeight: 10, }, ], } as unknown as DSLWidget; const outputDSL1 = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1224, snapColumns: 64, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 1040, containerStyle: "none", snapRows: 124, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: true, version: 70, minHeight: 1250, parentColumnSpace: 1, dynamicBindingPathList: [], leftColumn: 0, children: [ { schema: { __root_schema__: { children: { name: { children: {}, dataType: "string", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.name))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: "Text Input", sourceData: "John", isCustomField: false, accessor: "name", identifier: "name", position: 0, originalIdentifier: "name", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Name", }, date_of_birth: { children: {}, dataType: "string", defaultValue: '{{((sourceData, formData, fieldState) => (moment(sourceData.date_of_birth, "DD/MM/YYYY").format("YYYY-MM-DDTHH:mm:ss.sssZ")))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}', fieldType: "Datepicker", sourceData: "20/02/1990", isCustomField: false, accessor: "date_of_birth", identifier: "date_of_birth", position: 1, originalIdentifier: "date_of_birth", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", closeOnSelection: false, convertToISO: false, dateFormat: "DD/MM/YYYY", isDisabled: false, isRequired: false, isVisible: true, label: "Date Of Birth", maxDate: "2121-12-31T18:29:00.000Z", minDate: "1920-12-31T18:30:00.000Z", shortcuts: false, timePrecision: "minute", labelTextSize: "0.875rem", }, employee_id: { children: {}, dataType: "number", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.employee_id))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: "Number Input", sourceData: 1001, isCustomField: false, accessor: "employee_id", identifier: "employee_id", position: 2, originalIdentifier: "employee_id", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Employee Id", }, childStylesheet: { children: {}, dataType: "string", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.childStylesheet))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: "Text Input", sourceData: "asd", isCustomField: false, accessor: "childStylesheet", identifier: "childStylesheet", position: 3, originalIdentifier: "childStylesheet", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Child Stylesheet", }, }, dataType: "object", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: "Object", sourceData: { name: "John", date_of_birth: "20/02/1990", employee_id: 1001, childStylesheet: "asd", }, isCustomField: false, accessor: "__root_schema__", identifier: "__root_schema__", position: -1, originalIdentifier: "__root_schema__", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", cellBorderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", cellBoxShadow: "none", isDisabled: false, isRequired: false, isVisible: true, labelTextSize: "0.875rem", label: "", }, }, boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", borderColor: "#E0DEDE", widgetName: "JSONForm1", submitButtonStyles: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", buttonVariant: "PRIMARY", }, dynamicPropertyPathList: [ { key: "schema.__root_schema__.children.date_of_birth.defaultValue", }, ], displayName: "JSON Form", iconSVG: "/static/media/icon.5b428de12db9ad6a591955ead07f86e9.svg", topRow: 0, bottomRow: 50, fieldLimitExceeded: false, parentRowSpace: 10, title: "Form", type: "JSON_FORM_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 42.5625, dynamicTriggerPathList: [], leftColumn: 1, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, { key: "submitButtonStyles.buttonColor", }, { key: "submitButtonStyles.borderRadius", }, { key: "resetButtonStyles.buttonColor", }, { key: "resetButtonStyles.borderRadius", }, { key: "schema.__root_schema__.children.name.defaultValue", }, { key: "schema.__root_schema__.children.name.accentColor", }, { key: "schema.__root_schema__.children.name.borderRadius", }, { key: "schema.__root_schema__.children.date_of_birth.defaultValue", }, { key: "schema.__root_schema__.children.date_of_birth.accentColor", }, { key: "schema.__root_schema__.children.date_of_birth.borderRadius", }, { key: "schema.__root_schema__.children.employee_id.defaultValue", }, { key: "schema.__root_schema__.children.employee_id.accentColor", }, { key: "schema.__root_schema__.children.employee_id.borderRadius", }, { key: "schema.__root_schema__.defaultValue", }, { key: "schema.__root_schema__.borderRadius", }, { key: "schema.__root_schema__.cellBorderRadius", }, { key: "schema.__root_schema__.children.childStylesheet.defaultValue", }, { key: "schema.__root_schema__.children.childStylesheet.accentColor", }, { key: "schema.__root_schema__.children.childStylesheet.borderRadius", }, ], borderWidth: "1", sourceData: '{\n "name": "John",\n "date_of_birth": "20/02/1990",\n "employee_id": 1001,\n\t"childStylesheet":"asd"\n}', showReset: true, resetButtonLabel: "Reset", key: "4r1dire8mf", backgroundColor: "#fff", isDeprecated: false, rightColumn: 26, dynamicHeight: "FIXED", autoGenerateForm: true, widgetId: "136kliil8g", resetButtonStyles: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", buttonVariant: "SECONDARY", }, isVisible: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, scrollContents: true, fixedFooter: true, submitButtonLabel: "Submit", childStylesheet: { ARRAY: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", cellBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", cellBoxShadow: "none", }, OBJECT: { borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", cellBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", cellBoxShadow: "none", }, CHECKBOX: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, CURRENCY_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, DATEPICKER: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, EMAIL_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, MULTISELECT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, MULTILINE_TEXT_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, NUMBER_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, PASSWORD_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, PHONE_NUMBER_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, RADIO_GROUP: { accentColor: "{{appsmith.theme.colors.primaryColor}}", boxShadow: "none", }, SELECT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, SWITCH: { accentColor: "{{appsmith.theme.colors.primaryColor}}", boxShadow: "none", }, TEXT_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, }, disabledWhenInvalid: true, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", maxDynamicHeight: 9000, minDynamicHeight: 4, }, { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", borderColor: "#E0DEDE", isVisibleDownload: true, iconSVG: "/static/media/icon.db8a9cbd2acd22a31ea91cc37ea2a46c.svg", topRow: 2, isSortable: true, type: "TABLE_WIDGET_V2", inlineEditingSaveOption: "ROW_LEVEL", animateLoading: true, dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, { key: "primaryColumns.action.buttonColor", }, { key: "primaryColumns.action.borderRadius", }, { key: "primaryColumns.action.boxShadow", }, { key: "accentColor", }, { key: "borderRadius", }, { key: "boxShadow", }, ], leftColumn: 27, delimiter: ",", defaultSelectedRowIndex: 0, accentColor: "{{appsmith.theme.colors.primaryColor}}", isVisibleFilters: true, isVisible: true, enableClientSideSearch: true, version: 1, totalRecordsCount: 0, isLoading: false, childStylesheet: { button: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, menuButton: { menuColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, iconButton: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, editActions: { saveButtonColor: "{{appsmith.theme.colors.primaryColor}}", saveBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", discardButtonColor: "{{appsmith.theme.colors.primaryColor}}", discardBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, }, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", defaultSelectedRowIndices: [0], widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action"], dynamicPropertyPathList: [], displayName: "Table", bottomRow: 30, columnWidthMap: { task: 245, step: 62, status: 75, }, parentRowSpace: 10, hideCard: false, parentColumnSpace: 42.5625, borderWidth: "1", primaryColumns: { step: { index: 0, width: 150, id: "step", originalId: "step", alias: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "step", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["step"]))}}', validation: {}, labelColor: "#FFFFFF", }, task: { index: 1, width: 150, id: "task", originalId: "task", alias: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "task", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["task"]))}}', validation: {}, labelColor: "#FFFFFF", }, status: { index: 2, width: 150, id: "status", originalId: "status", alias: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDerived: false, label: "status", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["status"]))}}', validation: {}, labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", originalId: "action", alias: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "0.875rem", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isCellEditable: false, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["action"]))}}', validation: {}, labelColor: "#FFFFFF", buttonColor: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.colors.primaryColor))}}", borderRadius: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( appsmith.theme.borderRadius.appBorderRadius))}}", boxShadow: "{{Table1.processedTableData.map((currentRow, currentIndex) => ( 'none'))}}", }, }, key: "xi3zw81eiq", isDeprecated: false, rightColumn: 61, textSize: "0.875rem", widgetId: "6w4nk55npx", tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], label: "Data", searchKey: "", parentId: "0", renderMode: "CANVAS", horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", }, { boxShadow: "none", widgetName: "ButtonGroup1", isCanvas: false, displayName: "Button Group", iconSVG: "/static/media/icon.d6773218cfb61dcfa5f460d43371e30d.svg", searchTags: ["click", "submit"], topRow: 57, bottomRow: 61, parentRowSpace: 10, groupButtons: { groupButton1: { label: "Favorite", iconName: "heart", id: "groupButton1", widgetId: "", buttonType: "SIMPLE", placement: "CENTER", isVisible: true, isDisabled: false, index: 0, menuItems: {}, buttonColor: "{{appsmith.theme.colors.primaryColor}}", }, groupButton2: { label: "Add", iconName: "add", id: "groupButton2", buttonType: "SIMPLE", placement: "CENTER", widgetId: "", isVisible: true, isDisabled: false, index: 1, menuItems: {}, buttonColor: "{{appsmith.theme.colors.primaryColor}}", }, groupButton3: { label: "More", iconName: "more", id: "groupButton3", buttonType: "MENU", placement: "CENTER", widgetId: "", isVisible: true, isDisabled: false, index: 2, menuItems: { menuItem1: { label: "First Option", backgroundColor: "#FFFFFF", id: "menuItem1", widgetId: "", onClick: "", isVisible: true, isDisabled: false, index: 0, }, menuItem2: { label: "Second Option", backgroundColor: "#FFFFFF", id: "menuItem2", widgetId: "", onClick: "", isVisible: true, isDisabled: false, index: 1, }, menuItem3: { label: "Delete", iconName: "trash", iconColor: "#FFFFFF", iconAlign: "right", textColor: "#FFFFFF", backgroundColor: "#DD4B34", id: "menuItem3", widgetId: "", onClick: "", isVisible: true, isDisabled: false, index: 2, }, }, buttonColor: "{{appsmith.theme.colors.primaryColor}}", }, }, type: "BUTTON_GROUP_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 42.5625, leftColumn: 3, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "groupButtons.groupButton1.buttonColor", }, { key: "groupButtons.groupButton2.buttonColor", }, { key: "groupButtons.groupButton3.buttonColor", }, ], key: "kahzuua49o", orientation: "horizontal", isDeprecated: false, rightColumn: 27, widgetId: "tt1sptkg2z", isVisible: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, childStylesheet: { button: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", }, }, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", buttonVariant: "PRIMARY", }, { boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", widgetName: "Container1", borderColor: "#E0DEDE", isCanvas: true, displayName: "Container", iconSVG: "/static/media/icon.1977dca3370505e2db3a8e44cfd54907.svg", searchTags: ["div", "parent", "group"], topRow: 44, bottomRow: 96, parentRowSpace: 10, type: "CONTAINER_WIDGET", hideCard: false, shouldScrollContents: true, animateLoading: true, parentColumnSpace: 42.5625, leftColumn: 27, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, ], children: [ { widgetName: "Canvas1", displayName: "Canvas", topRow: 0, bottomRow: 520, parentRowSpace: 1, type: "CANVAS_WIDGET", canExtend: false, hideCard: true, minHeight: 520, parentColumnSpace: 1, leftColumn: 0, dynamicBindingPathList: [], children: [ { schema: { __root_schema__: { children: { name: { children: {}, dataType: "string", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.name))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", fieldType: "Text Input", sourceData: "John", isCustomField: false, accessor: "name", identifier: "name", position: 0, originalIdentifier: "name", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Name", }, date_of_birth: { children: {}, dataType: "string", defaultValue: '{{((sourceData, formData, fieldState) => (moment(sourceData.date_of_birth, "DD/MM/YYYY").format("YYYY-MM-DDTHH:mm:ss.sssZ")))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}', fieldType: "Datepicker", sourceData: "20/02/1990", isCustomField: false, accessor: "date_of_birth", identifier: "date_of_birth", position: 1, originalIdentifier: "date_of_birth", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", boxShadow: "none", closeOnSelection: false, convertToISO: false, dateFormat: "DD/MM/YYYY", isDisabled: false, isRequired: false, isVisible: true, label: "Date Of Birth", maxDate: "2121-12-31T18:29:00.000Z", minDate: "1920-12-31T18:30:00.000Z", shortcuts: false, timePrecision: "minute", labelTextSize: "0.875rem", }, employee_id: { children: {}, dataType: "number", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.employee_id))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", fieldType: "Number Input", sourceData: 1001, isCustomField: false, accessor: "employee_id", identifier: "employee_id", position: 2, originalIdentifier: "employee_id", accentColor: "{{((sourceData, formData, fieldState) => (appsmith.theme.colors.primaryColor))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Employee Id", }, }, dataType: "object", defaultValue: "{{((sourceData, formData, fieldState) => (sourceData))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", fieldType: "Object", sourceData: { name: "John", date_of_birth: "20/02/1990", employee_id: 1001, }, isCustomField: false, accessor: "__root_schema__", identifier: "__root_schema__", position: -1, originalIdentifier: "__root_schema__", borderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", boxShadow: "none", cellBorderRadius: "{{((sourceData, formData, fieldState) => (appsmith.theme.borderRadius.appBorderRadius))(JSONForm2.sourceData, JSONForm2.formData, JSONForm2.fieldState)}}", cellBoxShadow: "none", isDisabled: false, isRequired: false, isVisible: true, labelTextSize: "0.875rem", label: "", }, }, boxShadow: "{{appsmith.theme.boxShadow.appBoxShadow}}", borderColor: "#E0DEDE", widgetName: "JSONForm2", submitButtonStyles: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", buttonVariant: "PRIMARY", }, dynamicPropertyPathList: [ { key: "schema.__root_schema__.children.date_of_birth.defaultValue", }, ], displayName: "JSON Form", iconSVG: "/static/media/icon.5b428de12db9ad6a591955ead07f86e9.svg", topRow: 0, bottomRow: 50, fieldLimitExceeded: false, parentRowSpace: 10, title: "Form", type: "JSON_FORM_WIDGET", hideCard: false, animateLoading: true, parentColumnSpace: 15.6484375, dynamicTriggerPathList: [], leftColumn: 13, dynamicBindingPathList: [ { key: "borderRadius", }, { key: "boxShadow", }, { key: "submitButtonStyles.buttonColor", }, { key: "submitButtonStyles.borderRadius", }, { key: "resetButtonStyles.buttonColor", }, { key: "resetButtonStyles.borderRadius", }, { key: "schema.__root_schema__.children.name.defaultValue", }, { key: "schema.__root_schema__.children.name.accentColor", }, { key: "schema.__root_schema__.children.name.borderRadius", }, { key: "schema.__root_schema__.children.date_of_birth.defaultValue", }, { key: "schema.__root_schema__.children.date_of_birth.accentColor", }, { key: "schema.__root_schema__.children.date_of_birth.borderRadius", }, { key: "schema.__root_schema__.children.employee_id.defaultValue", }, { key: "schema.__root_schema__.children.employee_id.accentColor", }, { key: "schema.__root_schema__.children.employee_id.borderRadius", }, { key: "schema.__root_schema__.defaultValue", }, { key: "schema.__root_schema__.borderRadius", }, { key: "schema.__root_schema__.cellBorderRadius", }, ], borderWidth: "1", sourceData: { name: "John", date_of_birth: "20/02/1990", employee_id: 1001, }, showReset: true, resetButtonLabel: "Reset", key: "4r1dire8mf", backgroundColor: "#fff", isDeprecated: false, rightColumn: 38, dynamicHeight: "FIXED", autoGenerateForm: true, widgetId: "3m7vsrp7a8", resetButtonStyles: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", buttonVariant: "SECONDARY", }, isVisible: true, version: 1, parentId: "q71uafkl98", renderMode: "CANVAS", isLoading: false, scrollContents: true, fixedFooter: true, submitButtonLabel: "Submit", childStylesheet: { ARRAY: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", cellBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", cellBoxShadow: "none", }, OBJECT: { borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", cellBorderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", cellBoxShadow: "none", }, CHECKBOX: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", }, CURRENCY_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, DATEPICKER: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, EMAIL_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, MULTISELECT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, MULTILINE_TEXT_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, NUMBER_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, PASSWORD_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, PHONE_NUMBER_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, RADIO_GROUP: { accentColor: "{{appsmith.theme.colors.primaryColor}}", boxShadow: "none", }, SELECT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, SWITCH: { accentColor: "{{appsmith.theme.colors.primaryColor}}", boxShadow: "none", }, TEXT_INPUT: { accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, }, disabledWhenInvalid: true, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", maxDynamicHeight: 9000, minDynamicHeight: 4, }, ], key: "rkukmmul97", isDeprecated: false, rightColumn: 1021.5, detachFromLayout: true, widgetId: "q71uafkl98", containerStyle: "none", isVisible: true, version: 1, parentId: "08plhw35jc", renderMode: "CANVAS", isLoading: false, }, ], borderWidth: "1", key: "c5ggn97bsx", backgroundColor: "#FFFFFF", isDeprecated: false, rightColumn: 51, dynamicHeight: "AUTO_HEIGHT", widgetId: "08plhw35jc", containerStyle: "card", isVisible: true, version: 1, parentId: "0", renderMode: "CANVAS", isLoading: false, originalTopRow: 44, borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", maxDynamicHeight: 9000, originalBottomRow: 54, minDynamicHeight: 10, }, ], }; describe("Theming Migration - .migrateChildStylesheetFromDynamicBindingPathList", () => { it("removes childStylesheet paths from dynamicBindingPathList", () => { const resultDSL = migrateChildStylesheetFromDynamicBindingPathList( klona(inputDSL1), ); expect(resultDSL).toStrictEqual(outputDSL1); }); });
1,516
0
petrpan-code/appsmithorg/appsmith/app/client/src
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/WidgetUtils.test.ts
import { ButtonBorderRadiusTypes, ButtonVariantTypes, } from "components/constants"; import type { PropertyUpdates } from "WidgetProvider/constants"; import { RenderModes, TextSizes, WidgetHeightLimits, } from "constants/WidgetConstants"; import { remove } from "lodash"; import { getTheme, ThemeMode } from "selectors/themeSelectors"; import type { WidgetProps } from "./BaseWidget"; import { rgbaMigrationConstantV56 } from "../WidgetProvider/constants"; import { borderRadiusUtility, replaceRgbaMigrationConstant, boxShadowMigration, boxShadowUtility, fontSizeUtility, lightenColor, composePropertyUpdateHook, sanitizeKey, shouldUpdateWidgetHeightAutomatically, isAutoHeightEnabledForWidget, isAutoHeightEnabledForWidgetWithLimits, getWidgetMaxAutoHeight, getWidgetMinAutoHeight, isCompactMode, } from "./WidgetUtils"; import { getCustomTextColor, getCustomBackgroundColor, getCustomHoverColor, } from "./WidgetUtils"; const tableWidgetProps = { dynamicBindingPathList: [ { key: "primaryColumns.action.boxShadowColor", }, ], primaryColumns: { action: { boxShadow: "0px 0px 4px 3px rgba(0, 0, 0, 0.25)", boxShadowColor: ["red", "red", "red"], }, }, }; describe("validate widget utils button style functions", () => { const theme = getTheme(ThemeMode.LIGHT); // validate getCustomTextColor function it("getCustomTextColor - validate empty or undefined background color", () => { // background color is undefined const result = getCustomTextColor(theme); expect(result).toStrictEqual("#FFFFFF"); // background color is empty string const backgroundColor = ""; const expected = "#FFFFFF"; const result2 = getCustomTextColor(theme, backgroundColor); expect(result2).toStrictEqual(expected); }); it("getCustomTextColor - validate text color in case of dark or light background color", () => { // background color is dark const blueBackground = "#3366FF"; const expected1 = "#FFFFFF"; const result1 = getCustomTextColor(theme, blueBackground); expect(result1).toStrictEqual(expected1); // background color is light const yellowBackground = "#FFC13D"; const expected2 = "#FFFFFF"; const result2 = getCustomTextColor(theme, yellowBackground); expect(result2).toStrictEqual(expected2); }); // validate getCustomBackgroundColor function it("getCustomBackgroundColor - validate empty or undefined background color", () => { const expected = "none"; const result = getCustomBackgroundColor(); expect(result).toStrictEqual(expected); }); it("getCustomBackgroundColor - validate background color with primary button variant", () => { const backgroundColor = "#03b365"; const expected = "#03b365"; const result = getCustomBackgroundColor( ButtonVariantTypes.PRIMARY, backgroundColor, ); expect(result).toStrictEqual(expected); }); it("getCustomBackgroundColor - validate background color with secondary button variant", () => { const backgroundColor = "#03b365"; const expected = "none"; const result = getCustomBackgroundColor( ButtonVariantTypes.SECONDARY, backgroundColor, ); expect(result).toStrictEqual(expected); }); // validate getCustomHoverColor function it("getCustomHoverColor - validate empty or undefined background color or variant", () => { // background color and variant is both are undefined const expected = "hsl(0, 0%, 95%)"; const result = getCustomHoverColor(theme); expect(result).toStrictEqual(expected); // variant is undefined const backgroundColor = "#03b365"; const expected1 = "hsl(153, 97%, 31%)"; const result1 = getCustomHoverColor(theme, undefined, backgroundColor); expect(result1).toStrictEqual(expected1); }); // validate getCustomHoverColor function it("getCustomHoverColor - validate hover color for different variant", () => { const backgroundColor = "hsl(153, 97% ,36%)"; // variant : PRIMARY const expected1 = "hsl(153, 97%, 31%)"; const result1 = getCustomHoverColor( theme, ButtonVariantTypes.PRIMARY, backgroundColor, ); expect(result1).toStrictEqual(expected1); // variant : PRIMARY without background const expected2 = "hsl(0, 0%, 95%)"; const result2 = getCustomHoverColor(theme, ButtonVariantTypes.PRIMARY); expect(result2).toStrictEqual(expected2); // variant : SECONDARY const expected3 = "rgba(3, 181, 101, 0.1)"; const result3 = getCustomHoverColor( theme, ButtonVariantTypes.SECONDARY, backgroundColor, ); expect(result3).toStrictEqual(expected3); // variant : SECONDARY without background const expected4 = "rgba(255, 255, 255, 0.1)"; const result4 = getCustomHoverColor(theme, ButtonVariantTypes.SECONDARY); expect(result4).toStrictEqual(expected4); // variant : TERTIARY const expected5 = "rgba(3, 181, 101, 0.1)"; const result5 = getCustomHoverColor( theme, ButtonVariantTypes.TERTIARY, backgroundColor, ); expect(result5).toStrictEqual(expected5); // variant : TERTIARY without background const expected6 = "rgba(255, 255, 255, 0.1)"; const result6 = getCustomHoverColor(theme, ButtonVariantTypes.TERTIARY); expect(result6).toStrictEqual(expected6); }); it("Check if the color is lightened with lightenColor utility", () => { /** * Colors with : * 0% brightness = #000000, * > 40% brightness = #696969 * > 50% brightness = #8a8a8a * > 60% brightness = #b0b0b0 * > 70% brightness = #d6d4d4 */ const actualColors = [ "#000000", "#696969", "#8a8a8a", "#b0b0b0", "#d6d4d4", ]; const lightColors = ["#ededed", "#ededed", "#ededed", "#ededed", "#eeeded"]; actualColors.forEach((color, idx) => { expect(lightenColor(color)).toEqual(lightColors[idx]); }); }); }); describe(".sanitizeKey", () => { it("returns sanitized value when passed a valid string", () => { const inputAndExpectedOutput = [ ["lowercase", "lowercase"], ["__abc__", "__abc__"], ["lower_snake_case", "lower_snake_case"], ["UPPER_SNAKE_CASE", "UPPER_SNAKE_CASE"], ["PascalCase", "PascalCase"], ["camelCase", "camelCase"], ["lower-kebab-case", "lower_kebab_case"], ["UPPER_KEBAB-CASE", "UPPER_KEBAB_CASE"], ["Sentencecase", "Sentencecase"], ["", "_"], ["with space", "with_space"], ["with multiple spaces", "with_multiple__spaces"], ["with%special)characters", "with_special_characters"], ["with%$multiple_spl.)characters", "with__multiple_spl__characters"], ["1startingWithNumber", "_1startingWithNumber"], ]; inputAndExpectedOutput.forEach(([input, expectedOutput]) => { const result = sanitizeKey(input); expect(result).toEqual(expectedOutput); }); }); it("returns sanitized value when valid string with existing keys and reserved keys", () => { const existingKeys = [ "__id", "__restricted__", "firstName1", "_1age", "gender", "poll123", "poll124", "poll125", "address_", ]; const inputAndExpectedOutput = [ ["lowercase", "lowercase"], ["__abc__", "__abc__"], ["lower_snake_case", "lower_snake_case"], ["UPPER_SNAKE_CASE", "UPPER_SNAKE_CASE"], ["PascalCase", "PascalCase"], ["camelCase", "camelCase"], ["lower-kebab-case", "lower_kebab_case"], ["UPPER_KEBAB-CASE", "UPPER_KEBAB_CASE"], ["Sentencecase", "Sentencecase"], ["", "_"], ["with space", "with_space"], ["with multiple spaces", "with_multiple__spaces"], ["with%special)characters", "with_special_characters"], ["with%$multiple_spl.)characters", "with__multiple_spl__characters"], ["1startingWithNumber", "_1startingWithNumber"], ["1startingWithNumber", "_1startingWithNumber"], ["firstName", "firstName"], ["firstName1", "firstName2"], ["1age", "_1age1"], ["address&", "address_1"], ["%&id", "__id1"], ["%&restricted*(", "__restricted__1"], ["poll130", "poll130"], ["poll124", "poll126"], ["हिन्दि", "xn__j2bd4cyac6f"], ["😃", "xn__h28h"], ]; inputAndExpectedOutput.forEach(([input, expectedOutput]) => { const result = sanitizeKey(input, { existingKeys, }); expect(result).toEqual(expectedOutput); }); }); }); describe("Test widget utility functions", () => { it("case: fontSizeUtility returns the font sizes based on variant", () => { const expectedFontSize = "0.75rem"; expect(fontSizeUtility(TextSizes.PARAGRAPH2)).toEqual(expectedFontSize); }); it("case: borderRadiusUtility returns the borderRadius based on borderRadius variant", () => { const expectedBorderRadius = "0.375rem"; expect(borderRadiusUtility(ButtonBorderRadiusTypes.ROUNDED)).toEqual( expectedBorderRadius, ); }); it("case: replaceRgbaMigrationConstant returns the new boxShadow by replacing default boxShadowColor with new boxShadowColor", () => { const boxShadow = "0px 0px 4px 3px rgba(0, 0, 0, 0.25)"; const boxShadowColor = "red"; const expectedBoxShadow = "0px 0px 4px 3px red"; expect(replaceRgbaMigrationConstant(boxShadow, boxShadowColor)).toEqual( expectedBoxShadow, ); }); it("case: boxShadowUtility returns the new boxShadow", () => { const variants = [ "VARIANT1", "VARIANT2", "VARIANT3", "VARIANT4", "VARIANT5", ]; let newBoxShadowColor = rgbaMigrationConstantV56; let expectedBoxShadows = [ `0px 0px 4px 3px ${newBoxShadowColor}`, `3px 3px 4px ${newBoxShadowColor}`, `0px 1px 3px ${newBoxShadowColor}`, `2px 2px 0px ${newBoxShadowColor}`, `-2px -2px 0px ${newBoxShadowColor}`, ]; // Check the boxShadow when the boxShadowColor is set to default; variants.forEach((value: string, index: number) => { expect(boxShadowUtility(value, newBoxShadowColor)).toEqual( expectedBoxShadows[index], ); }); // Check the boxShadow when the boxShadowColor is set to custom color; newBoxShadowColor = "red"; expectedBoxShadows = [ `0px 0px 4px 3px ${newBoxShadowColor}`, `3px 3px 4px ${newBoxShadowColor}`, `0px 1px 3px ${newBoxShadowColor}`, `2px 2px 0px ${newBoxShadowColor}`, `-2px -2px 0px ${newBoxShadowColor}`, ]; variants.forEach((value: string, index: number) => { expect(boxShadowUtility(value, newBoxShadowColor)).toEqual( expectedBoxShadows[index], ); }); }); it("case: boxShadowMigration returns correct boxShadow whenever boxShadow and boxShadowColor ar dynamic", () => { /** * Function usd inside table widget cell properties for Icon and menu button types. * This function is used to run theming migration boxShadow and boxShadowColor has dynamic bindings * Function runs for the following scenarios, when: * 1. boxShadow: Static; boxShadowColor: Dynamic * 2. boxShadow: Dynamic; boxShadowColor: Static * 3. boxShadow: Dynamic; boxShadowColor: empty * 4. boxShadow: Dynamic; boxShadowColor: dynamic */ // Case 1: expect( boxShadowMigration( tableWidgetProps.dynamicBindingPathList as any, "action", "0px 0px 4px 3px rgba(0, 0, 0, 0.25)", "red", ), ).toEqual("0px 0px 4px 3px red"); // Case 2 & 3: // Make boxShadow dynamic /** * 1. Add the boxShadow to the DBPL * 2. Remove boxShadowColor from the DBPL * 3. Assign the action.boxShadowcolor as a static value. * 4. Assign the action.boxShadowcolor as a empty value. */ tableWidgetProps.dynamicBindingPathList.push({ key: "primaryColumns.action.boxShadow", }); // Remove boxShadowColor from dynamicBindingPathList remove( tableWidgetProps.dynamicBindingPathList, (value: { key: string }) => value.key === "primaryColumns.action.boxShadowColor", ); // Assign values to boxShadow and boxShadowColor tableWidgetProps.primaryColumns.action.boxShadow = "VARIANT1"; tableWidgetProps.primaryColumns.action.boxShadowColor = "blue" as any; let newBoxShadow = boxShadowMigration( tableWidgetProps.dynamicBindingPathList as any, "action", tableWidgetProps.primaryColumns.action.boxShadow, tableWidgetProps.primaryColumns.action.boxShadowColor, ); expect(newBoxShadow).toEqual("0px 0px 4px 3px blue"); tableWidgetProps.primaryColumns.action.boxShadow = "VARIANT1"; tableWidgetProps.primaryColumns.action.boxShadowColor = "" as any; // Add empty boxShadowColor. newBoxShadow = boxShadowMigration( tableWidgetProps.dynamicBindingPathList as any, "action", tableWidgetProps.primaryColumns.action.boxShadow, tableWidgetProps.primaryColumns.action.boxShadowColor, ); expect(newBoxShadow).toEqual("0px 0px 4px 3px rgba(0, 0, 0, 0.25)"); // Case 4: // Add boxShadow and boxShadowColor to the dynamicBindingPathList tableWidgetProps.dynamicBindingPathList = [ ...tableWidgetProps.dynamicBindingPathList, { key: "primaryColumns.action.boxShadow", }, { key: "primaryColumns.action.boxShadowColor", }, ]; // Assign values to boxShadow and boxShadowColor tableWidgetProps.primaryColumns.action.boxShadow = "VARIANT1"; tableWidgetProps.primaryColumns.action.boxShadowColor = [ "orange", "orange", "orange", ]; newBoxShadow = boxShadowMigration( tableWidgetProps.dynamicBindingPathList as any, "action", tableWidgetProps.primaryColumns.action.boxShadow, tableWidgetProps.primaryColumns.action.boxShadowColor[0], ); expect(newBoxShadow).toEqual("0px 0px 4px 3px orange"); tableWidgetProps.primaryColumns.action.boxShadow = "VARIANT1"; tableWidgetProps.primaryColumns.action.boxShadowColor = ["", "", ""] as any; // Add empty boxShadowColor when dynamic // Add empty boxShadowColor. newBoxShadow = boxShadowMigration( tableWidgetProps.dynamicBindingPathList as any, "action", tableWidgetProps.primaryColumns.action.boxShadow, tableWidgetProps.primaryColumns.action.boxShadowColor[0], ); expect(newBoxShadow).toEqual("0px 0px 4px 3px rgba(0, 0, 0, 0.25)"); }); }); type composePropertyUpdateHookInputType = Array< ( props: unknown, propertyPath: string, propertyValue: any, ) => PropertyUpdates[] | undefined >; describe("composePropertyUpdateHook", () => { it("should test that it's returning a function", () => { expect(typeof composePropertyUpdateHook([() => undefined])).toEqual( "function", ); }); it("should test that calling the function concats the returned values of input functions in the given order", () => { const input = [() => [1], () => [2], () => [3], () => [4]]; const expected = [1, 2, 3, 4]; expect( composePropertyUpdateHook( input as unknown as composePropertyUpdateHookInputType, )(null, "", null), ).toEqual(expected); }); it("should test that calling the function concats the returned values of input functions in the given order and ignores undefined", () => { const input = [() => [1], () => undefined, () => [3], () => [4]]; const expected = [1, 3, 4]; expect( composePropertyUpdateHook( input as unknown as composePropertyUpdateHookInputType, )(null, "", null), ).toEqual(expected); }); it("should test that calling the function without any function returns undefined", () => { const input: any = []; const expected = undefined; expect(composePropertyUpdateHook(input)(null, "", null)).toEqual(expected); }); }); const DUMMY_WIDGET: WidgetProps = { bottomRow: 0, isLoading: false, leftColumn: 0, parentColumnSpace: 0, parentRowSpace: 0, renderMode: RenderModes.CANVAS, rightColumn: 0, topRow: 0, type: "SKELETON_WIDGET", version: 2, widgetId: "", widgetName: "", }; describe("Auto Height Utils", () => { it("should return true if withLimits is true and widget has AUTO_HEIGHT_WITH_LIMITS", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT_WITH_LIMITS", }; const result = isAutoHeightEnabledForWidgetWithLimits(props); expect(result).toBe(true); }); it("should return false if withLimits is true and widget has AUTO_HEIGHT", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT", }; const result = isAutoHeightEnabledForWidgetWithLimits(props); expect(result).toBe(false); }); it("should return true if withLimits is false and widget has AUTO_HEIGHT", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT", }; const result = isAutoHeightEnabledForWidget(props); expect(result).toBe(true); }); it("should return false withLimits is false and widget has FIXED", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "FIXED", }; const result = isAutoHeightEnabledForWidget(props); expect(result).toBe(false); }); it("should return false withLimits is true and widget has FIXED", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "FIXED", }; const result = isAutoHeightEnabledForWidgetWithLimits(props); expect(result).toBe(false); }); it("should return 9000 if widget has AUTO_HEIGHT", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT", maxDynamicHeight: 20, }; const result = getWidgetMaxAutoHeight(props); expect(result).toBe(WidgetHeightLimits.MAX_HEIGHT_IN_ROWS); }); it("should return 20 if widget has AUTO_HEIGHT_WITH_LIMITS", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT_WITH_LIMITS", maxDynamicHeight: 20, }; const result = getWidgetMaxAutoHeight(props); expect(result).toBe(20); }); it("should return 9000 if widget has AUTO_HEIGHT_WITH_LIMITS and maxDynamicHeight is undefined", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT_WITH_LIMITS", maxDynamicHeight: undefined, }; const result = getWidgetMaxAutoHeight(props); expect(result).toBe(WidgetHeightLimits.MAX_HEIGHT_IN_ROWS); }); it("should return undefined if widget is FIXED ", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "FIXED", maxDynamicHeight: undefined, }; const result = getWidgetMaxAutoHeight(props); expect(result).toBeUndefined(); }); it("should return 20 if widget has AUTO_HEIGHT and props has 20", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT", minDynamicHeight: 20, }; const result = getWidgetMinAutoHeight(props); expect(result).toBe(20); }); it("should return 20 if widget has AUTO_HEIGHT_WITH_LIMITS", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT_WITH_LIMITS", minDynamicHeight: 20, }; const result = getWidgetMinAutoHeight(props); expect(result).toBe(20); }); it("should return 4 if widget has AUTO_HEIGHT_WITH_LIMITS and minDynamicHeight is undefined", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT_WITH_LIMITS", minDynamicHeight: undefined, }; const result = getWidgetMinAutoHeight(props); expect(result).toBe(WidgetHeightLimits.MIN_HEIGHT_IN_ROWS); }); it("should return undefined if widget is FIXED ", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "FIXED", minDynamicHeight: undefined, }; const result = getWidgetMinAutoHeight(props); expect(result).toBeUndefined(); }); }); describe("Should Update Widget Height Automatically?", () => { it("Multiple scenario tests", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT_WITH_LIMITS", minDynamicHeight: 19, maxDynamicHeight: 40, topRow: 20, bottomRow: 40, }; const inputs = [ 600, // Is beyond max height of 40 rows, 560, // Is beyond max height of 40 rows 220, // Is within 20 and 40 rows limits 180, // Is below the min of 20 rows 200, // Is the same as current height 190, // Is exactly min value 400, // Is exactly max value 0, // Is below the min possible value 100, // Is below the min possible value ]; const expected = [ true, // because currentHeight is not close to maxDynamicHeight true, // because currentheight is not close to maxDynamicHeight true, true, // because we need to go as low as possible (minDynamicHeight) true, true, true, true, // because we need to go as low as possible (minDynamicHeight) true, // because we need to go as low as possible (minDynamicHeight) ]; inputs.forEach((input, index) => { const result = shouldUpdateWidgetHeightAutomatically(input, props); expect(result).toStrictEqual(expected[index]); }); }); it("When height is below min rows, should update, no matter the expectations", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT_WITH_LIMITS", minDynamicHeight: 19, maxDynamicHeight: 40, topRow: 20, bottomRow: 25, }; const input = 0; const expected = true; const result = shouldUpdateWidgetHeightAutomatically(input, props); expect(result).toStrictEqual(expected); }); it("When height is above max rows, should update, no matter the expectations", () => { const props = { ...DUMMY_WIDGET, dynamicHeight: "AUTO_HEIGHT_WITH_LIMITS", minDynamicHeight: 19, maxDynamicHeight: 40, topRow: 20, bottomRow: 65, }; const input = 0; const expected = true; const result = shouldUpdateWidgetHeightAutomatically(input, props); expect(result).toStrictEqual(expected); }); it("should return correct value for isCompactMode", () => { const compactHeight = 40; const unCompactHeight = 41; expect(isCompactMode(compactHeight)).toBeTruthy(); expect(isCompactMode(unCompactHeight)).toBeFalsy(); }); });
1,520
0
petrpan-code/appsmithorg/appsmith/app/client/src
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/utils.test.ts
import { getVideoConstraints } from "./utils"; describe("getVideoConstraints", () => { test("returns default video constraints when no deviceId and not mobile", () => { const prevConstraints = { width: { ideal: 1280 }, height: { ideal: 720 } }; const defaultCamera = "environment"; const isMobile = false; const constraints = getVideoConstraints( prevConstraints, isMobile, defaultCamera, ); expect(constraints).toEqual(prevConstraints); }); test("returns video constraints with deviceId when deviceId is provided", () => { const prevConstraints = { width: { ideal: 1280 }, height: { ideal: 720 } }; const defaultCamera = "environment"; const isMobile = false; const deviceId = "test-device-id"; const constraints = getVideoConstraints( prevConstraints, isMobile, defaultCamera, deviceId, ); expect(constraints).toEqual({ ...prevConstraints, deviceId: "test-device-id", }); }); test("returns video constraints with facingMode when isMobile is true", () => { const prevConstraints = { width: { ideal: 1280 }, height: { ideal: 720 } }; const defaultCamera = "environment"; const isMobile = true; const constraints = getVideoConstraints( prevConstraints, isMobile, defaultCamera, ); expect(constraints).toEqual({ ...prevConstraints, facingMode: { ideal: "environment" }, }); }); test("returns video constraints with both deviceId and facingMode when provided", () => { const prevConstraints = { width: { ideal: 1280 }, height: { ideal: 720 } }; const defaultCamera = "environment"; const isMobile = true; const deviceId = "test-device-id"; const constraints = getVideoConstraints( prevConstraints, isMobile, defaultCamera, deviceId, ); expect(constraints).toEqual({ ...prevConstraints, deviceId: "test-device-id", facingMode: { ideal: "environment" }, }); }); });
1,531
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/AudioWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/AudioWidget/widget/index.test.tsx
import type { PropertyPaneControlConfig } from "constants/PropertyControlConstants"; import AudioWidget from "."; const urlTests = [ { url: "https://appsmith.com/", isValid: true }, { url: "http://appsmith.com/", isValid: true }, { url: "appsmith.com/", isValid: true }, { url: "appsmith.com", isValid: true }, { url: "release.appsmith.com", isValid: true }, { url: "appsmith.com/audio.mp3", isValid: true }, { url: "appsmith./audio.mp3", isValid: false }, { url: "https://appsmith.com/randompath/somefile.mp3", isValid: true }, { url: "https://appsmith.com/randompath/some file.mp3", isValid: true }, { url: "random string", isValid: false }, { url: "blob:https://dev.appsmith.com/9db94f56-5e32-4b18-2758-64c21a7f4610", isValid: true, }, ]; describe("urlRegexValidation", () => { const dataSectionProperties: PropertyPaneControlConfig[] = AudioWidget.getPropertyPaneContentConfig().filter( (x) => x.sectionName === "Data", )[0].children; const urlPropertyControl = dataSectionProperties.filter( (x) => x.propertyName === "url", )[0]; const regEx = urlPropertyControl.validation?.params?.regex; it("validate existence of regEx", () => { expect(regEx).toBeDefined(); }); it("test regEx", () => { urlTests.forEach((test) => { if (test.isValid) expect(test.url).toMatch(regEx || ""); else expect(test.url).not.toMatch(regEx || ""); }); }); });
1,569
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/CustomEChartIFrameComponent.test.tsx
import type { ChartComponentConnectedProps } from "."; import type { ChartData } from "../constants"; import { DefaultEChartConfig, LabelOrientation, DefaultFusionChartConfig, } from "../constants"; import React from "react"; import { render } from "@testing-library/react"; import "@testing-library/jest-dom"; import { CustomEChartIFrameComponent } from "./CustomEChartIFrameComponent"; const seriesData1: ChartData = { seriesName: "series1", data: [{ x: "x1", y: 1000 }], color: "series1color", }; const seriesData2: ChartData = { seriesName: "series2", data: [{ x: "x1", y: 2000 }], color: "series2color", }; const defaultProps: ChartComponentConnectedProps = { allowScroll: true, showDataPointLabel: true, chartData: { seriesID1: seriesData1, seriesID2: seriesData2, }, chartName: "chart name", chartType: "AREA_CHART", customEChartConfig: DefaultEChartConfig, customFusionChartConfig: DefaultFusionChartConfig, hasOnDataPointClick: true, isVisible: true, isLoading: false, setAdaptiveYMin: false, labelOrientation: LabelOrientation.AUTO, onDataPointClick: () => {}, widgetId: "widgetID", xAxisName: "xaxisname", yAxisName: "yaxisname", borderRadius: "1", boxShadow: "1", primaryColor: "primarycolor", fontFamily: "fontfamily", dimensions: { componentWidth: 1000, componentHeight: 1000 }, parentColumnSpace: 1, parentRowSpace: 1, topRow: 0, bottomRow: 100, leftColumn: 0, rightColumn: 100, needsOverlay: false, }; let container: any; describe("CustomEChartIFrameComponent", () => { beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); container = null; }); it("returns the iframe with sandbox attributes", () => { const { container } = render( <CustomEChartIFrameComponent {...defaultProps} />, ); const iFrameElement = container.querySelector("iframe"); expect(iFrameElement).toBeInTheDocument(); expect(iFrameElement).toHaveAttribute("sandbox", "allow-scripts"); const overlay = container.querySelector( "div[data-testid='iframe-overlay']", ); expect(overlay).not.toBeInTheDocument(); }); it("renders the overlay if needsOverlay is set to true", () => { const props: ChartComponentConnectedProps = JSON.parse( JSON.stringify(defaultProps), ); props.needsOverlay = true; const { container } = render(<CustomEChartIFrameComponent {...props} />); const iFrameElement = container.querySelector("iframe"); expect(iFrameElement).toBeInTheDocument(); const overlay = container.querySelector( "div[data-testid='iframe-overlay']", ); expect(overlay).toBeInTheDocument(); }); });
1,571
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/EChartsConfigurationBuilder.test.ts
import { Colors } from "constants/Colors"; import type { ChartComponentProps } from "."; import type { ChartData } from "../constants"; import { LabelOrientation } from "../constants"; import { EChartsConfigurationBuilder } from "./EChartsConfigurationBuilder"; describe("EChartsConfigurationBuilder", () => { const builder = new EChartsConfigurationBuilder(); const longestLabels = { x: "x1", y: "y1" }; const dataZoomConfig = [ { filterMode: "filter", bottom: 30, start: "0", end: "50", type: "slider", show: true, height: 30, }, { filterMode: "filter", start: "0", end: "50", type: "inside", show: true, }, ]; const chartData1: ChartData = { seriesName: "series1", data: [{ x: "x1", y: "y1" }], color: "series1color", }; const chartData2: ChartData = { seriesName: "series2", data: [{ x: "x1", y: "y1" }], color: "series2color", }; const chartData = { seriesID1: chartData1, seriesID2: chartData2 }; const defaultProps: ChartComponentProps = { allowScroll: false, showDataPointLabel: true, chartData: chartData, chartName: "chart name", chartType: "LINE_CHART", customEChartConfig: {}, customFusionChartConfig: { type: "type", dataSource: undefined }, hasOnDataPointClick: false, isVisible: true, isLoading: false, setAdaptiveYMin: false, labelOrientation: LabelOrientation.ROTATE, onDataPointClick: (point) => { point.x; }, widgetId: "widgetID", xAxisName: "xaxisname", yAxisName: "yaxisname", borderRadius: "1", boxShadow: "1", primaryColor: "primarycolor", fontFamily: "fontfamily", dimensions: { componentWidth: 1000, componentHeight: 1000 }, parentColumnSpace: 1, parentRowSpace: 1, topRow: 0, bottomRow: 0, leftColumn: 0, rightColumn: 0, }; const defaultExpectedConfig = { dataZoom: [], legend: { align: "left", left: "center", orient: "horizontal", textStyle: { fontFamily: "fontfamily" }, padding: [5, 50], top: 50, type: "scroll", show: true, }, grid: { top: 110, bottom: 52, left: 50, show: false }, title: { show: true, text: defaultProps.chartName, left: "center", padding: [15, 50], textStyle: { fontFamily: "fontfamily", fontSize: 24, color: Colors.THUNDER, overflow: "truncate", width: 900, }, }, tooltip: { trigger: "item", }, xAxis: { type: "category", axisLabel: { rotate: 90, fontFamily: "fontfamily", color: Colors.DOVE_GRAY2, show: true, width: 2, overflow: "truncate", }, show: true, name: "xaxisname", nameLocation: "middle", nameGap: 12, nameTextStyle: { fontSize: 14, fontFamily: "fontfamily", color: Colors.DOVE_GRAY2, }, }, yAxis: { axisLabel: { fontFamily: "fontfamily", color: Colors.DOVE_GRAY2, overflow: "truncate", show: true, width: 2, }, show: true, name: "yaxisname", nameLocation: "middle", nameGap: 20, nameTextStyle: { fontSize: 14, fontFamily: "fontfamily", color: Colors.DOVE_GRAY2, }, }, series: [ { type: "line", name: "series1", itemStyle: { color: "series1color" }, label: { show: true, position: "top", }, }, { type: "line", name: "series2", itemStyle: { color: "series2color" }, label: { show: true, position: "top", }, }, ], }; it("1. builds a right chart configuration", () => { const output = builder.prepareEChartConfig( defaultProps, chartData, longestLabels, ); expect(output).toEqual(defaultExpectedConfig); }); describe("2. Allow scroll variations", () => { it("2.1 data zoom property isn't present if allowScroll is false", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.allowScroll = false; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.dataZoom = []; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output).toStrictEqual(expectedConfig); }); it("2.2 Data zoom property is present if allowScroll is true and chart type isn't PIE_CHART", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.allowScroll = true; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.dataZoom = dataZoomConfig; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.dataZoom).toStrictEqual(expectedConfig.dataZoom); }); it("2.3 data zoom property isn't present if chart type is pie chart", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "PIE_CHART"; props.allowScroll = true; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.dataZoom = []; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.dataZoom).toStrictEqual(expectedConfig.dataZoom); }); }); describe("3. Title configuration variations", () => { it("3.1 includes default title config for non PIE_CHART chart types", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "BAR_CHART"; const expectedConfig: any = { ...defaultExpectedConfig }; expectedConfig.title = { text: "chart name", left: "center", padding: [15, 50], show: true, textStyle: { fontFamily: "fontfamily", fontSize: 24, color: Colors.THUNDER, overflow: "truncate", width: 900, }, }; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.title).toStrictEqual(expectedConfig.title); }); it("3.2 includes layout infomration for pie chart chart type", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "PIE_CHART"; const expectedConfig: any = { ...defaultExpectedConfig }; expectedConfig.title = [ { text: "chart name", left: "center", padding: [15, 50], show: true, textStyle: { fontFamily: "fontfamily", fontSize: 24, color: Colors.THUNDER, overflow: "truncate", width: 900, }, }, { top: 90, left: 495, textAlign: "center", text: "series1", }, { top: 90, left: 495, textAlign: "center", text: "series2", }, ]; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.title).toStrictEqual(expectedConfig.title); }); }); describe("4. x-axis configuration variations", () => { it("4.1 returns appropriate config type for BAR_CHART", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "BAR_CHART"; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.xAxis.type = "value"; expectedConfig.xAxis.axisLabel.rotate = 0; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.xAxis).toStrictEqual(expectedConfig.xAxis); }); it("4.2 should configuration for label orientation SLANT", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.labelOrientation = LabelOrientation.SLANT; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.xAxis.axisLabel.rotate = 45; // slant configuration needs rotate = 45; expectedConfig.xAxis.axisLabel.width = 2; expectedConfig.xAxis.nameGap = 12; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.xAxis).toStrictEqual(expectedConfig.xAxis); }); describe("4.3 when label orientation is rotate", () => { it("4.3.1 returns correct configuration for label orientation ROTATE", () => { const labelRotatedProps = JSON.parse(JSON.stringify(defaultProps)); labelRotatedProps.labelOrientation = LabelOrientation.ROTATE; const labelRotatedConfig = JSON.parse( JSON.stringify(defaultExpectedConfig), ); labelRotatedConfig.xAxis.axisLabel.rotate = 90; labelRotatedConfig.xAxis.nameGap = 12; labelRotatedConfig.grid.bottom = 52; const output = builder.prepareEChartConfig( labelRotatedProps, chartData, longestLabels, ); expect(output).toStrictEqual(labelRotatedConfig); }); }); it("4.4 returns correct configuration for label orientation AUTO", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.labelOrientation = LabelOrientation.AUTO; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.xAxis.axisLabel = { color: Colors.DOVE_GRAY2, fontFamily: "fontfamily", rotate: 0, show: true, }; expectedConfig.xAxis.nameGap = 40; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.xAxis).toStrictEqual(expectedConfig.xAxis); }); it("4.5 returns correct xAxis configuration for PIE_CHART", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "PIE_CHART"; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.xAxis = { type: "category", axisLabel: { ...defaultExpectedConfig.xAxis.axisLabel, width: -50 }, show: false, }; expectedConfig.xAxis.axisLabel.show = false; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.xAxis).toStrictEqual(expectedConfig.xAxis); }); }); describe("5. y axis configuration variations", () => { it("5.1 returns appropriate y axis type for BAR_CHART", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "BAR_CHART"; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.yAxis.type = "category"; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.yAxis).toStrictEqual(expectedConfig.yAxis); }); it("5.2 returns correct y axis config for adaptive y axis option", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.setAdaptiveYMin = true; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.yAxis.min = "dataMin"; // "datamin" means that the y axis is adaptive in echarts const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output).toStrictEqual(expectedConfig); }); it("5.3 includes only axisLabel configuration for y axis when chart type is PIE_CHART", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "PIE_CHART"; const config = { axisLabel: defaultExpectedConfig.yAxis.axisLabel, show: true, }; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.yAxis).toStrictEqual(config); }); }); describe("6. series configuration", () => { it("6.1 chooses the app primary color for first series if no series color is present", () => { const props = JSON.parse(JSON.stringify(defaultProps)); const modifiedChartData = JSON.parse(JSON.stringify(chartData)); modifiedChartData.seriesID1.color = ""; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.series[0].itemStyle.color = "primarycolor"; const output = builder.prepareEChartConfig( props, modifiedChartData, longestLabels, ); expect(output).toStrictEqual(expectedConfig); }); it("6.2 doesn't choose the app primary color for second series if its series color isn't present", () => { const props = JSON.parse(JSON.stringify(defaultProps)); const modifiedChartData = JSON.parse(JSON.stringify(chartData)); modifiedChartData.seriesID2.color = ""; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.series[1].itemStyle.color = ""; const output = builder.prepareEChartConfig( props, modifiedChartData, longestLabels, ); expect(output).toStrictEqual(expectedConfig); }); it("6.3 chooses the appropriate configuration for bar chart", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "BAR_CHART"; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.series[0].type = "bar"; expectedConfig.series[0].label.position = "right"; expectedConfig.series[1].type = "bar"; expectedConfig.series[1].label.position = "right"; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.series).toStrictEqual(expectedConfig.series); }); it("6.4 chooses the appropriate configuration for line chart", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "LINE_CHART"; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.series[0].type = "line"; expectedConfig.series[1].type = "line"; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.series).toStrictEqual(expectedConfig.series); }); it("6.5 chooses the appropriate configuration for column chart", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "COLUMN_CHART"; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.series[0].type = "bar"; expectedConfig.series[1].type = "bar"; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.series).toStrictEqual(expectedConfig.series); }); it("6.6 chooses the appropriate configuration for area chart", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "AREA_CHART"; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.series[0].type = "line"; expectedConfig.series[1].type = "line"; expectedConfig.series[0].areaStyle = {}; expectedConfig.series[1].areaStyle = {}; const output = builder.prepareEChartConfig( props, chartData, longestLabels, ); expect(output.series).toStrictEqual(expectedConfig.series); }); it("6.7 chooses the appropriate configuration for pie chart", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "PIE_CHART"; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.series = [ { type: "pie", top: 110, bottom: 30, name: "series1", encode: { itemName: "Category", tooltip: "seriesID1", value: "seriesID1", }, label: { show: true, fontFamily: "fontfamily", color: Colors.DOVE_GRAY2, formatter: "{b} : {d}%", }, }, ]; const output = builder.prepareEChartConfig( props, { seriesID1: chartData1, }, longestLabels, ); expect(output.series).toStrictEqual(expectedConfig.series); }); it("6.8 chooses a default series name for the legend if series name prop is empty", () => { const props = JSON.parse(JSON.stringify(defaultProps)); const chartDataParams = JSON.parse(JSON.stringify(chartData)); chartDataParams.seriesID1.seriesName = ""; let output = builder.prepareEChartConfig( props, chartDataParams, longestLabels, ); let firstSeriesName = (output.series as any[])[0].name; expect(firstSeriesName).toEqual("Series"); chartDataParams.seriesID1.seriesName = undefined; output = builder.prepareEChartConfig( props, chartDataParams, longestLabels, ); firstSeriesName = (output.series as any[])[0].name; expect(firstSeriesName).toEqual("Series"); }); it("6.9 PIE-CHART chooses a default series name for the legend if series name prop is empty", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "PIE_CHART"; const chartDataParams = JSON.parse(JSON.stringify(chartData1)); chartDataParams.seriesName = ""; let output = builder.prepareEChartConfig( props, { seriesID1: chartDataParams, }, longestLabels, ); let firstSeriesName = (output.series as any[])[0].name; expect(firstSeriesName).toEqual("Series"); chartDataParams.seriesName = undefined; output = builder.prepareEChartConfig( props, { seriesID1: chartDataParams, }, longestLabels, ); firstSeriesName = (output.series as any[])[0].name; expect(firstSeriesName).toEqual("Series"); }); it("6.10 shows labels on series data if Show Labels if true otherwise false", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.showDataPointLabel = true; const expectedConfig: any = JSON.parse( JSON.stringify(defaultExpectedConfig), ); expectedConfig.series[0].label.show = true; expectedConfig.series[1].label.show = true; let output = builder.prepareEChartConfig(props, chartData, longestLabels); expect(output.series).toStrictEqual(expectedConfig.series); props.showDataPointLabel = false; expectedConfig.series[0].label.show = false; expectedConfig.series[1].label.show = false; output = builder.prepareEChartConfig(props, chartData, longestLabels); expect(output.series).toStrictEqual(expectedConfig.series); }); it("6.11 shows labels on series data if Show Labels if true, else false for PIE Chart as well", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "PIE_CHART"; props.showDataPointLabel = true; let output = builder.prepareEChartConfig(props, chartData, longestLabels); let seriesConfig = output.series as Record< string, Record<string, unknown> >[]; expect(seriesConfig[0].label.show).toEqual(true); props.showDataPointLabel = false; output = builder.prepareEChartConfig(props, chartData, longestLabels); seriesConfig = output.series as Record<string, Record<string, unknown>>[]; expect(seriesConfig[0].label.show).toEqual(false); }); }); });
1,573
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/EChartsDatasetBuilder.test.ts
import { EChartsDatasetBuilder } from "./EChartsDatasetBuilder"; import type { ChartData, ChartType } from "../constants"; describe("EChartsConfigurationBuilder", () => { describe("filteredChartData", () => { const chartData1: ChartData = { seriesName: "series1", data: [{ x: "x1", y: "y1" }], color: "series1color", }; const chartData2: ChartData = { seriesName: "series2", data: [{ x: "Product1", y: "y2" }], color: "series2color", }; const chartData = { seriesID1: chartData1, seriesID2: chartData2 }; it("1. returns all series data if chart type is not pie", () => { const chartType: ChartType = "AREA_CHART"; const builder = new EChartsDatasetBuilder(chartType, chartData); expect(builder.filteredChartData).toEqual(chartData); }); it("2. returns only the first series data if chart type is pie", () => { const chartType: ChartType = "PIE_CHART"; const builder = new EChartsDatasetBuilder(chartType, chartData); const expectedOutput = { seriesID1: chartData1, }; expect(builder.filteredChartData).toEqual(expectedOutput); }); }); describe("datasetFromData", () => { it("builds the right chart data source from chart widget props", () => { const chartData1: ChartData = { seriesName: "series1", data: [{ x: "x1", y: "y1" }], color: "series1color", }; const chartData2: ChartData = { seriesName: "series2", data: [{ x: "Product1", y: "y2" }], color: "series2color", }; const chartData3: ChartData = { seriesName: "series3", data: [{ x: "x1", y: "y3" }], color: "series2color", }; const chartData = { seriesID1: chartData1, seriesID2: chartData2, seriesID3: chartData3, }; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsDatasetBuilder(chartType, chartData); const expectedChartDataSource = { source: [ ["Category", "seriesID1", "seriesID2", "seriesID3"], ["x1", "y1", "", "y3"], ["Product1", "", "y2", ""], ], }; expect(builder.datasetFromData()).toEqual(expectedChartDataSource); }); }); describe("longestDataLabels", () => { it("returns the x and y values with longest number of characters in chart data", () => { const longestXLabel = "longestXLabel"; const longestYValue = "1234.56"; const chartData1: ChartData = { seriesName: "series1", data: [ { x: "smallLabel", y: "123" }, { x: longestXLabel, y: "1234" }, ], color: "series1color", }; const chartData2: ChartData = { seriesName: "series2", data: [ { x: "largeLabel", y: longestYValue }, { x: "largerLabel", y: "12" }, ], color: "series2color", }; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsDatasetBuilder(chartType, { series1ID: chartData1, series2ID: chartData2, }); builder.datasetFromData(); expect(builder.longestDataLabels()).toEqual({ x: longestXLabel, y: longestYValue, }); }); }); });
1,576
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/helpers.test.ts
import type { ChartType } from "../constants"; import { parseOnDataPointClickParams, parseOnDataPointClickForCustomEChart, parseOnDataPointClickForCustomFusionChart, } from "./helpers"; describe("parseOnDataPointClickParams", () => { it("returns appropriate chart selected point from user click data", () => { const chartType: ChartType = "CUSTOM_ECHART"; const event = { data: { dataKey: "dataValue", }, }; const parsedEvent = parseOnDataPointClickParams(event, chartType); expect(parsedEvent.rawEventData).toEqual(event); }); }); describe("parseOnDataPointClickForCustomEChart", () => { it("return correct rawEventData", () => { const event = { data: { dataKey: "dataValue", }, seriesName: "seriesName", }; const parsedEvent = parseOnDataPointClickForCustomEChart(event); expect(parsedEvent.rawEventData).toEqual(event); }); it("omits mouse event data", () => { const event = { data: { dataKey: "dataValue", }, seriesName: "seriesName", event: { mouseEventClickX: 1, mouseEventClickY: 1, }, }; const parsedEvent = parseOnDataPointClickForCustomEChart(event); expect(Object.keys(parsedEvent.rawEventData ?? [])).toEqual([ "data", "seriesName", ]); }); it("returns other properties of selected point as undefined", () => { const event = { data: { dataKey: "dataValue", }, seriesName: "seriesName", event: { mouseEventClickX: 1, mouseEventClickY: 1, }, }; const parsedEvent = parseOnDataPointClickForCustomEChart(event); expect(parsedEvent.x).toBeUndefined(); expect(parsedEvent.y).toBeUndefined(); expect(parsedEvent.seriesTitle).toBeUndefined(); expect(parsedEvent.rawEventData).not.toBeUndefined(); }); }); describe("parseOnDataPointClickForCustomFusionChart", () => { it("includes raw event data", () => { const eventData = { dataKey: "dataValue", }; const event = { data: eventData, otherKey: "otherValue", }; const parsedEvent = parseOnDataPointClickForCustomFusionChart(event); expect(parsedEvent.rawEventData).toEqual(eventData); }); it("returns x and y with values from appropriate fields", () => { const eventData = { dataKey: "dataValue", categoryLabel: "x value", dataValue: "y value", datasetName: "series name", }; const event = { data: eventData, otherKey: "otherValue", }; const parsedEvent = parseOnDataPointClickForCustomFusionChart(event); expect(parsedEvent.rawEventData).toEqual(eventData); expect(parsedEvent.x).toEqual("x value"); expect(parsedEvent.y).toEqual("y value"); expect(parsedEvent.seriesTitle).toEqual("series name"); }); it("returns x, y and seriesTitle as undefined if appropriate fields are not present", () => { const eventData = { dataKey: "dataValue", }; const event = { data: eventData, otherKey: "otherValue", }; const parsedEvent = parseOnDataPointClickForCustomFusionChart(event); expect(parsedEvent.rawEventData).toEqual(eventData); expect(parsedEvent.x).toBeUndefined(); expect(parsedEvent.y).toBeUndefined(); expect(parsedEvent.seriesTitle).toBeUndefined(); }); });
1,578
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/index.test.tsx
import ChartComponent from "."; import type { ChartComponentProps } from "."; import type { ChartData } from "../constants"; import { DefaultEChartConfig, LabelOrientation, DefaultFusionChartConfig, } from "../constants"; import React from "react"; import { render } from "@testing-library/react"; import "@testing-library/jest-dom"; import userEvent from "@testing-library/user-event"; import { screen } from "@testing-library/react"; import { Provider } from "react-redux"; import configureMockStore from "redux-mock-store"; let container: any; describe("Chart Widget", () => { const seriesData1: ChartData = { seriesName: "series1", data: [{ x: "x1", y: 1000 }], color: "series1color", }; const seriesData2: ChartData = { seriesName: "series2", data: [{ x: "x1", y: 2000 }], color: "series2color", }; const defaultProps: ChartComponentProps = { allowScroll: true, showDataPointLabel: true, chartData: { seriesID1: seriesData1, seriesID2: seriesData2, }, chartName: "chart name", chartType: "AREA_CHART", customEChartConfig: DefaultEChartConfig, customFusionChartConfig: DefaultFusionChartConfig, hasOnDataPointClick: true, isVisible: true, isLoading: false, setAdaptiveYMin: false, labelOrientation: LabelOrientation.AUTO, onDataPointClick: (point) => { return point; }, widgetId: "widgetID", xAxisName: "xaxisname", yAxisName: "yaxisname", borderRadius: "1", boxShadow: "1", primaryColor: "primarycolor", fontFamily: "fontfamily", dimensions: { componentWidth: 1000, componentHeight: 1000 }, parentColumnSpace: 1, parentRowSpace: 1, topRow: 0, bottomRow: 100, leftColumn: 0, rightColumn: 100, }; beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); container = null; }); const mockStore = configureMockStore(); const store = mockStore({ entities: { canvasWidgets: {}, }, ui: { widgetDragResize: { selectedWidgets: [], }, }, }); it("1. renders the correct library for chart type", async () => { const { container, getByText, rerender } = render( <Provider store={store}> <ChartComponent {...defaultProps} /> </Provider>, ); const xAxisLabel = getByText("xaxisname"); expect(xAxisLabel).toBeInTheDocument(); let echartsContainer = container.querySelector("#widgetIDechart-container"); expect(echartsContainer).toBeInTheDocument(); let fusionContainer = container.querySelector( "#widgetIDcustom-fusion-chart-container", ); expect(fusionContainer).not.toBeInTheDocument(); let props = { ...defaultProps }; props.chartType = "CUSTOM_FUSION_CHART"; rerender( <Provider store={store}> <ChartComponent {...props} /> </Provider>, ); echartsContainer = container.querySelector("#widgetIDechart-container"); expect(echartsContainer).not.toBeInTheDocument(); fusionContainer = container.querySelector( "#widgetIDcustom-fusion-chart-container", ); expect(fusionContainer).toBeInTheDocument(); props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "CUSTOM_ECHART"; rerender( <Provider store={store}> <ChartComponent {...props} /> </Provider>, ); echartsContainer = container.querySelector("iframe"); expect(echartsContainer).toBeInTheDocument(); }); it("2. successfully switches sequence of basic chart/custom fusion chart/basic chart/custom echart", async () => { // First render with Area Chart let props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "AREA_CHART"; const { container, getByText, rerender } = render( <Provider store={store}> <ChartComponent {...props} /> </Provider>, ); let xAxisLabel = getByText("xaxisname"); expect(xAxisLabel).toBeInTheDocument(); let echartsContainer = container.querySelector("#widgetIDechart-container"); expect(echartsContainer).toBeInTheDocument(); let fusionContainer = container.querySelector( "#widgetIDcustom-fusion-chart-container", ); expect(fusionContainer).not.toBeInTheDocument(); // Second render with fusion charts props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "CUSTOM_FUSION_CHART"; rerender( <Provider store={store}> <ChartComponent {...props} /> </Provider>, ); echartsContainer = container.querySelector("#widgetIDechart-container"); expect(echartsContainer).not.toBeInTheDocument(); fusionContainer = container.querySelector( "#widgetIDcustom-fusion-chart-container", ); expect(fusionContainer).toBeInTheDocument(); // Third render with Area charts again. props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "AREA_CHART"; rerender( <Provider store={store}> <ChartComponent {...props} /> </Provider>, ); xAxisLabel = getByText("xaxisname"); expect(xAxisLabel).toBeInTheDocument(); echartsContainer = container.querySelector("#widgetIDechart-container"); expect(echartsContainer).toBeInTheDocument(); // Render Custom EChart props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "CUSTOM_ECHART"; rerender( <Provider store={store}> <ChartComponent {...props} /> </Provider>, ); echartsContainer = container.querySelector("iframe"); expect(echartsContainer).toBeInTheDocument(); }); it("3. adds a click event when user adds a click callback", async () => { const mockCallback = jest.fn((params) => params); const props = { ...defaultProps }; props.onDataPointClick = (point) => { point; mockCallback(point); }; render( <Provider store={store}> <ChartComponent {...props} /> </Provider>, ); expect(mockCallback.mock.calls.length).toEqual(0); const el = await screen.findByText("1000"); userEvent.click(el); expect(mockCallback.mock.calls.length).toEqual(1); }); });
1,580
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/LayoutBuilders/EChartsElementVisibilityCalculator.test.ts
import { EChartElementVisibilityCalculator } from "./EChartsElementVisibilityCalculator"; import type { EChartElementLayoutParams } from "./EChartsElementVisibilityCalculator"; describe("EChartsElementVisibilityCalculator", () => { describe("visibility calculator", () => { it("returns no elements if element minHeight is equal to gridMinimumHeight", () => { const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: 10, maxHeight: 10, position: "top", }, { elementName: "element2", minHeight: 10, maxHeight: 10, position: "bottom", }, ]; const gridMinimumHeight = 80; const heightAvailable = 80; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: 0, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(0); }); it("fits as many elements possible within the height available", () => { const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: 10, maxHeight: 10, position: "top", }, { elementName: "element2", minHeight: 30, maxHeight: 30, position: "bottom", }, ]; const gridMinimumHeight = 80; const heightAvailable = 120; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: 0, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(2); }); it("excludes elements that can't fit within the height available", () => { const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: 10, maxHeight: 10, position: "top", }, { elementName: "element2", minHeight: 30, maxHeight: 30, position: "bottom", }, ]; const gridMinimumHeight = 80; const heightAvailable = 100; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: 0, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(1); expect(builder.visibleElements[0].elementName).toEqual("element1"); }); it("excludes lower priority fitting elements if higher priority elements can't fit", () => { const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: 30, maxHeight: 30, position: "top", }, { elementName: "element2", minHeight: 10, maxHeight: 10, position: "bottom", }, ]; const gridMinimumHeight = 80; const heightAvailable = 90; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: 0, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(0); }); }); describe("offsets calculator", () => { it("includes the height of visible elements in calculating top and bottom grid offsets", () => { const topElementHeight = 10; const bottomElementHeight = 30; const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: topElementHeight, maxHeight: topElementHeight, position: "top", }, { elementName: "element2", minHeight: bottomElementHeight, maxHeight: bottomElementHeight, position: "bottom", }, ]; const gridMinimumHeight = 80; const heightAvailable = 120; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: 0, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(2); const offsets = builder.calculateOffsets(); expect(offsets.top).toEqual(topElementHeight); expect(offsets.bottom).toEqual(bottomElementHeight); }); it("uses custom top padding if no top element is included in config", () => { const elementHeight = 10; const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: elementHeight, maxHeight: elementHeight, position: "bottom", }, ]; const gridMinimumHeight = 80; const heightAvailable = 90; const customPadding = 5; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: customPadding, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(1); const offsets = builder.calculateOffsets(); expect(offsets.top).toEqual(customPadding); expect(offsets.bottom).toEqual(elementHeight); }); it("uses custom bottom padding if no bottom element is included in config", () => { const elementHeight = 10; const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: elementHeight, maxHeight: elementHeight, position: "top", }, ]; const gridMinimumHeight = 80; const heightAvailable = 90; const customPadding = 5; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: customPadding, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(1); const offsets = builder.calculateOffsets(); expect(offsets.top).toEqual(elementHeight); expect(offsets.bottom).toEqual(customPadding); }); it("allocates max height to element if there is remaining space inside the widget", () => { const minElementHeight = 10; const maxElementHeight = 40; const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: minElementHeight, maxHeight: maxElementHeight, position: "bottom", }, ]; const gridMinimumHeight = 80; const heightAvailable = 120; const customPadding = 5; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: customPadding, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(1); expect(builder.visibleElements[0].height).toEqual(maxElementHeight); const offsets = builder.calculateOffsets(); expect(offsets.top).toEqual(customPadding); expect(offsets.bottom).toEqual(maxElementHeight); }); it("allocates max height possible to element if there is remaining space inside the widget", () => { const minElementHeight = 10; const maxElementHeight = 40; const elements: EChartElementLayoutParams[] = [ { elementName: "element1", minHeight: minElementHeight, maxHeight: maxElementHeight, position: "bottom", }, ]; const gridMinimumHeight = 80; const heightAvailable = 110; const customPadding = 5; const builder = new EChartElementVisibilityCalculator({ height: heightAvailable, padding: customPadding, gridMinimumHeight: gridMinimumHeight, layoutConfigs: elements, }); expect(builder.visibleElements.length).toEqual(1); expect(builder.visibleElements[0].height).toEqual(30); const offsets = builder.calculateOffsets(); expect(offsets.top).toEqual(customPadding); expect(offsets.bottom).toEqual(30); }); }); });
1,582
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/LayoutBuilders/EChartsLayoutBuilder.test.ts
import { LabelOrientation } from "widgets/ChartWidget/constants"; import { EChartsLayoutBuilder } from "./EChartsLayoutBuilder"; const font = "14px Nunito Sans"; describe("priority order of layout", () => { it("returns the correct priority order", () => { const builder = new EChartsLayoutBuilder({ allowScroll: false, widgetHeight: 0, widgetWidth: 0, labelOrientation: LabelOrientation.AUTO, chartType: "LINE_CHART", chartTitle: "chartTitle", seriesConfigs: {}, font: font, longestLabels: { x: "123", y: "123" }, }); expect(builder.priorityOrderOfInclusion).toEqual([ "legend", "title", "xAxis", "scrollBar", ]); }); }); describe("layout configs to include", () => { it("includes scroll bar if allow scroll is true", () => { const allowScroll = true; const builder = new EChartsLayoutBuilder({ allowScroll: allowScroll, widgetHeight: 0, widgetWidth: 0, labelOrientation: LabelOrientation.AUTO, seriesConfigs: { series1ID: { data: [], seriesName: "series name", }, }, chartType: "LINE_CHART", chartTitle: "chartTitle", font: font, longestLabels: { x: "123", y: "123" }, }); const output = builder.configsToInclude(); expect(output).toEqual(["legend", "title", "xAxis", "scrollBar"]); }); it("excludes scroll bar if allow scroll is false", () => { const allowScroll = false; const builder = new EChartsLayoutBuilder({ allowScroll: allowScroll, widgetHeight: 0, widgetWidth: 0, labelOrientation: LabelOrientation.AUTO, seriesConfigs: { series1ID: { data: [], seriesName: "series name", }, }, chartType: "LINE_CHART", chartTitle: "chartTitle", font: font, longestLabels: { x: "123", y: "123" }, }); const output = builder.configsToInclude(); expect(output).toEqual(["legend", "title", "xAxis"]); }); it("doesn't include title if chart title length is 0", () => { const emptyChartTitle = ""; const allowScroll = false; const builder = new EChartsLayoutBuilder({ allowScroll: allowScroll, widgetHeight: 0, widgetWidth: 0, labelOrientation: LabelOrientation.AUTO, chartType: "LINE_CHART", font: font, seriesConfigs: { series1ID: { data: [], seriesName: "series name", }, }, longestLabels: { x: "123", y: "123" }, chartTitle: emptyChartTitle, }); const output = builder.configsToInclude(); expect(output).toEqual(["legend", "xAxis"]); }); it("includes legend if number of series data is more than 1", () => { const seriesConfigs = { series1ID: { data: [], }, series2ID: { data: [], }, }; const builder = new EChartsLayoutBuilder({ allowScroll: true, widgetHeight: 0, widgetWidth: 0, labelOrientation: LabelOrientation.AUTO, seriesConfigs: seriesConfigs, chartType: "LINE_CHART", chartTitle: "chartTitle", font: font, longestLabels: { x: "123", y: "123" }, }); const output = builder.configsToInclude(); expect(output).toEqual(["legend", "title", "xAxis", "scrollBar"]); }); it("doesn't include legend if number of series data is 0", () => { const seriesConfigs = {}; const builder = new EChartsLayoutBuilder({ allowScroll: true, widgetHeight: 0, widgetWidth: 0, labelOrientation: LabelOrientation.AUTO, seriesConfigs: seriesConfigs, chartType: "LINE_CHART", chartTitle: "chartTitle", font: font, longestLabels: { x: "123", y: "123" }, }); const output = builder.configsToInclude(); expect(output).toEqual(["title", "xAxis", "scrollBar"]); }); it("if number of series configs is 1, doesn't include legend if series name is missing", () => { const seriesConfigs = { series1ID: { data: [], }, }; const builder = new EChartsLayoutBuilder({ allowScroll: true, widgetHeight: 0, widgetWidth: 0, labelOrientation: LabelOrientation.AUTO, seriesConfigs: seriesConfigs, chartType: "LINE_CHART", chartTitle: "chartTitle", font: font, longestLabels: { x: "123", y: "123" }, }); const output = builder.configsToInclude(); expect(output).toEqual(["title", "xAxis", "scrollBar"]); }); it("if number of series configs is 1, includes legend if series name is present", () => { const seriesConfigs = { series1ID: { seriesName: "seriesNamePresent", data: [], }, }; const builder = new EChartsLayoutBuilder({ allowScroll: true, widgetHeight: 0, widgetWidth: 0, labelOrientation: LabelOrientation.AUTO, seriesConfigs: seriesConfigs, chartType: "LINE_CHART", chartTitle: "chartTitle", font: font, longestLabels: { x: "123", y: "123" }, }); const output = builder.configsToInclude(); expect(output).toEqual(["legend", "title", "xAxis", "scrollBar"]); }); }); describe("legend top offset", () => { it("legend top offset is 50 if title is visible", () => { const chartTitle = "chartTitle"; const builder = new EChartsLayoutBuilder({ allowScroll: true, widgetHeight: 400, widgetWidth: 300, labelOrientation: LabelOrientation.AUTO, chartType: "LINE_CHART", font: font, seriesConfigs: {}, chartTitle: chartTitle, longestLabels: { x: "123", y: "123" }, }); const output = builder.layoutConfigForElements(); expect(output.title.show).toEqual(true); expect(output.legend.top).toEqual(50); }); it("legend top offset is 0 if title is not visible", () => { const emptyChartTitle = ""; const builder = new EChartsLayoutBuilder({ allowScroll: true, widgetHeight: 400, widgetWidth: 300, labelOrientation: LabelOrientation.AUTO, chartType: "LINE_CHART", font: font, seriesConfigs: {}, longestLabels: { x: "123", y: "123" }, chartTitle: emptyChartTitle, }); const output = builder.layoutConfigForElements(); expect(output.title.show).toEqual(false); expect(output.legend.top).toEqual(0); }); }); describe("layout configs", () => { it("generates correct chart layout config", () => { const builder = new EChartsLayoutBuilder({ allowScroll: true, widgetHeight: 400, widgetWidth: 300, labelOrientation: LabelOrientation.ROTATE, chartType: "LINE_CHART", font: font, longestLabels: { x: "123", y: "123" }, seriesConfigs: { seriesID1: { data: [], seriesName: "seriesName", }, }, chartTitle: "chartTitle", }); const output = builder.layoutConfigForElements(); expect(output).toEqual({ xAxis: { show: true, nameGap: 13, axisLabel: { width: 3, overflow: "truncate", }, }, legend: { show: true, top: 50, }, title: { show: true, }, scrollBar: { show: true, bottom: 30, height: 30, }, grid: { top: 110, bottom: 113, left: 51, }, yAxis: { show: true, nameGap: 21, axisLabel: { width: 3, overflow: "truncate", }, }, }); }); });
1,584
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/LayoutBuilders/EChartsXAxisLayoutBuilder.test.ts
import type { ChartType } from "../../constants"; import { LabelOrientation } from "../../constants"; import { EChartsXAxisLayoutBuilder } from "./EChartsXAxisLayoutBuilder"; const font = "14px Nunito Sans"; describe("EChartsXAxisLayoutBuilder", () => { describe("width for xaxis labels", () => { it("returns a default width when label orientation is auto", () => { const labelOrientation = LabelOrientation.AUTO; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: "LINE_CHART", font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.widthForXAxisLabels()).toEqual(0); }); describe("when label orientation is not auto", () => { it("when chart type is not BAR_CHART, returns the width of the longest x label", () => { const labelOrientation = LabelOrientation.ROTATE; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: "LINE_CHART", font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.widthForXAxisLabels()).toEqual(6); }); it("when chart type is BAR_CHART, returns the width of the longest y label", () => { const labelOrientation = LabelOrientation.ROTATE; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: "BAR_CHART", font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.widthForXAxisLabels()).toEqual(3); }); }); }); describe("maxHeightForLabels", () => { it("returns a default height when label orientation is auto", () => { const labelOrientation = LabelOrientation.AUTO; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: "LINE_CHART", font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.defaultHeightForXAxisLabels).toEqual(30); expect(builder.gapBetweenLabelAndName).toEqual(10); expect(builder.maxHeightForXAxisLabels()).toEqual(40); }); it("returns sum of label width and an offset when label orientation is not auto", () => { const labelOrientation = LabelOrientation.ROTATE; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: "LINE_CHART", font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.gapBetweenLabelAndName).toEqual(10); expect(builder.widthForXAxisLabels()).toEqual(6); expect(builder.maxHeightForXAxisLabels()).toEqual(16); }); }); describe("minHeightForLabels", () => { it("returns 0 height for pie chart", () => { const labelOrientation = LabelOrientation.AUTO; const chartType: ChartType = "PIE_CHART"; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: chartType, font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.minHeightForLabels()).toEqual(0); }); describe("chart type is not PIE_CHART", () => { it("returns a fixed height when label orientation is auto", () => { const labelOrientation = LabelOrientation.AUTO; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: chartType, font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.defaultHeightForXAxisLabels).toEqual(30); expect(builder.gapBetweenLabelAndName).toEqual(10); expect(builder.defaultHeightForXAxisName).toEqual(40); expect(builder.minHeightForLabels()).toEqual(80); }); it("returns a fixed height when label orientation is not auto", () => { const labelOrientation = LabelOrientation.ROTATE; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: chartType, font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.defaultHeightForRotatedLabels).toEqual(50); expect(builder.gapBetweenLabelAndName).toEqual(10); expect(builder.defaultHeightForXAxisName).toEqual(40); expect(builder.minHeightForLabels()).toEqual(100); }); }); }); describe("maxHeightForXAxis", () => { it("when chart type is PIE_CHART, it returns zero height", () => { const labelOrientation = LabelOrientation.ROTATE; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: "PIE_CHART", font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.maxHeightForXAxis()).toEqual(0); }); it("when chart type is not PIE_CHART, it returns sum of max height of labels and an offset", () => { const labelOrientation = LabelOrientation.ROTATE; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: "LINE_CHART", font: font, longestLabel: { x: "123456", y: "123" }, }); expect(builder.maxHeightForXAxisLabels()).toEqual(16); expect(builder.defaultHeightForXAxisName).toEqual(40); expect(builder.maxHeightForXAxis()).toEqual(56); }); }); describe("heightConfigForLabels", () => { it("returns the minHeight and maxHeight required for labels", () => { const labelOrientation = LabelOrientation.ROTATE; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: chartType, font: font, longestLabel: { x: "this is a long text with width more than min width for xaxis labels", y: "123", }, }); expect(builder.minHeightForLabels()).toEqual(100); expect(builder.maxHeightForXAxis()).toEqual(117); expect(builder.heightConfigForXAxis()).toEqual({ minHeight: 100, maxHeight: 117, }); }); it("returns minHeight the same as maxHeight if minHeight >= maxHeight", () => { const labelOrientation = LabelOrientation.ROTATE; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: chartType, font: font, longestLabel: { x: "123456", y: "123", }, }); expect(builder.minHeightForLabels()).toEqual(100); expect(builder.maxHeightForXAxis()).toEqual(56); expect(builder.heightConfigForXAxis()).toEqual({ minHeight: 56, maxHeight: 56, }); }); }); describe("axisLabelConfig", () => { it("when label orientation is AUTO, it returns empty axisLabelConfig", () => { const labelOrientation = LabelOrientation.AUTO; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: chartType, font: font, longestLabel: { x: "123456", y: "123", }, }); expect(builder.axisLabelConfig(100)).toEqual({}); }); it("when label orientation is not AUTO, it returns width for labels excluding padding and x axis name offsets", () => { const labelOrientation = LabelOrientation.ROTATE; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: chartType, font: font, longestLabel: { x: "123456", y: "123", }, }); const allocatedXAxisHeight = 100; const labelWidth = allocatedXAxisHeight - builder.defaultHeightForXAxisName - builder.gapBetweenLabelAndName; const expectedConfig = { width: labelWidth, overflow: "truncate", }; expect(builder.axisLabelConfig(allocatedXAxisHeight)).toEqual( expectedConfig, ); }); }); describe("xAxis config", () => { it("returns xAxis config with gap between labels and xaxis name equal to allocated height minus default xaxis name height", () => { const labelOrientation = LabelOrientation.ROTATE; const chartType: ChartType = "LINE_CHART"; const builder = new EChartsXAxisLayoutBuilder({ labelOrientation: labelOrientation, chartType: chartType, font: font, longestLabel: { x: "123456", y: "123", }, }); expect(builder.defaultHeightForXAxisName).toEqual(40); const allocatedXAxisHeight = 100; const labelWidth = allocatedXAxisHeight - builder.defaultHeightForXAxisName - builder.gapBetweenLabelAndName; const nameGap = allocatedXAxisHeight - builder.defaultHeightForXAxisName; expect(builder.defaultHeightForXAxisName).toEqual(40); expect(nameGap).toEqual(60); const expectedConfig = { nameGap: nameGap, axisLabel: { width: labelWidth, overflow: "truncate", }, }; expect(builder.configForXAxis(allocatedXAxisHeight)).toEqual( expectedConfig, ); }); }); // describe("height of x axis labels", () => { // it("when label orientation isn't auto, it is equal to sum of width of x axis labels and a fixed offset", () => { // const labelOrientation = LabelOrientation.SLANT; // const builder = new EChartsXAxisLayoutBuilder( // labelOrientation, // "LINE_CHART", // ); // expect(builder.gapBetweenLabelAndName).toEqual(10); // expect(builder.widthForXAxisLabels()).toEqual(50); // expect(builder.heightForXAxisLabels()).toEqual(60); // }); // it("is equal to a default height when label orientation is auto", () => { // const labelOrientation = LabelOrientation.AUTO; // const builder = new EChartsXAxisLayoutBuilder( // labelOrientation, // "LINE_CHART", // ); // expect(builder.gapBetweenLabelAndName).toEqual(10); // expect(builder.defaultHeightForXAxisLabels).toEqual(30); // expect(builder.heightForXAxisLabels()).toEqual(40); // }); // }); // describe("height of x axis", () => { // it("is equal to sum of height of x axis labels and an offset", () => { // const labelOrientation = LabelOrientation.SLANT; // const builder = new EChartsXAxisLayoutBuilder( // labelOrientation, // "LINE_CHART", // ); // expect(builder.defaultHeightForXAxisName).toEqual(40); // expect(builder.heightForXAxisLabels()).toEqual(60); // expect(builder.heightForXAxis()).toEqual(100); // }); // it("is equal to 0 when chart type is pie chart", () => { // const labelOrientation = LabelOrientation.SLANT; // const chartType: ChartType = "PIE_CHART"; // const builder = new EChartsXAxisLayoutBuilder( // labelOrientation, // chartType, // ); // expect(builder.heightForXAxis()).toEqual(0); // }); // }); // describe("config for x axis", () => { // it("returns x axis config for chart layout", () => { // const labelOrientation = LabelOrientation.SLANT; // const chartType: ChartType = "LINE_CHART"; // const builder = new EChartsXAxisLayoutBuilder( // labelOrientation, // chartType, // ); // const expectedOutput = { // nameGap: 60, // axisLabel: { // width: 50, // }, // }; // expect(builder.configForXAxis()).toEqual(expectedOutput); // }); // }); });
1,586
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/component/LayoutBuilders/EChartsYAxisLayoutBuilder.test.ts
import { EChartsYAxisLayoutBuilder } from "./EChartsYAxisLayoutBuilder"; const font = "14px Nunito Sans"; describe("EChartsYAxisLayoutBuilder", () => { describe("maxWidthForLabels", () => { it("returns the max width for labels to equal sum of label width in pixels and an offset", () => { const builder = new EChartsYAxisLayoutBuilder({ widgetWidth: 100, chartType: "LINE_CHART", font: font, longestLabel: { x: "x label", y: "123456" }, }); expect(builder.maxWidthForLabels()).toEqual(6); }); }); describe("width for labels", () => { it("if available space is greater than label width, it returns value equal to label width", () => { const builder = new EChartsYAxisLayoutBuilder({ widgetWidth: 300, chartType: "LINE_CHART", font: font, longestLabel: { x: "x label", y: "123456" }, }); expect(builder.minimumWidth).toEqual(150); expect(builder.maxWidthForLabels()).toEqual(6); expect(builder.widthForLabels()).toEqual(6); }); it("if available space is lesser than label width, it returns available space", () => { const builder = new EChartsYAxisLayoutBuilder({ widgetWidth: 160, chartType: "LINE_CHART", font: font, longestLabel: { x: "x label", y: "123456" }, }); expect(builder.minimumWidth).toEqual(150); expect(builder.maxWidthForLabels()).toEqual(6); expect(builder.widthForLabels()).toEqual(6); }); }); describe("visibility of y axis config", () => { it("shows y axis if width is more than minimum width", () => { const widgetWidth = 160; const builder = new EChartsYAxisLayoutBuilder({ widgetWidth: widgetWidth, chartType: "LINE_CHART", font: font, longestLabel: { x: "x label", y: "123456" }, }); expect(builder.minimumWidth).toEqual(150); expect(builder.showYAxisConfig()).toEqual(true); }); it("hides y axis if width is more than minimum width", () => { const widgetWidth = 149; const builder = new EChartsYAxisLayoutBuilder({ widgetWidth: widgetWidth, chartType: "LINE_CHART", font: font, longestLabel: { x: "x label", y: "123456" }, }); expect(builder.minimumWidth).toEqual(150); expect(builder.showYAxisConfig()).toEqual(false); }); }); describe("y axis grid left offset", () => { it("when y axis is visible, offset is equal to sum of label width and offsets", () => { const widgetWidth = 160; const builder = new EChartsYAxisLayoutBuilder({ widgetWidth: widgetWidth, chartType: "LINE_CHART", font: font, longestLabel: { x: "x label", y: "123456" }, }); expect(builder.minimumWidth).toEqual(150); expect(builder.showYAxisConfig()).toEqual(true); expect(builder.labelsWidth).toEqual(6); expect(builder.gridLeftOffset()).toEqual(54); }); it("when y axis is not visible, offset is 5", () => { const widgetWidth = 149; const builder = new EChartsYAxisLayoutBuilder({ widgetWidth: widgetWidth, chartType: "LINE_CHART", font: font, longestLabel: { x: "x label", y: "123456" }, }); expect(builder.minimumWidth).toEqual(150); expect(builder.showYAxisConfig()).toEqual(false); expect(builder.gridLeftOffset()).toEqual(5); }); }); describe("y axis config", () => { it("returns correct y axis config based on props", () => { const widgetWidth = 160; const builder = new EChartsYAxisLayoutBuilder({ widgetWidth: widgetWidth, chartType: "LINE_CHART", font: font, longestLabel: { x: "x label", y: "123456" }, }); const expectedOutput = { show: true, nameGap: 24, axisLabel: { width: 6, overflow: "truncate", }, }; expect(builder.config()).toEqual(expectedOutput); }); }); });
1,588
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/widget/SyntaxErrorsEvaluation.test.ts
import { LabelOrientation } from "../constants"; import type { ChartWidgetProps } from "."; import type { ChartData } from "../constants"; import type { WidgetError } from "widgets/BaseWidget"; import { syntaxErrorsFromProps } from "./SyntaxErrorsEvaluation"; import { RenderModes } from "constants/WidgetConstants"; describe("SyntaxErrorsEvaluation", () => { const seriesData1: ChartData = { seriesName: "series1", data: [{ x: "x1", y: 1 }], color: "series1color", }; const seriesData2: ChartData = { seriesName: "series2", data: [{ x: "x1", y: 2 }], color: "series2color", }; const defaultProps: ChartWidgetProps = { allowScroll: true, chartData: { seriesID1: seriesData1, seriesID2: seriesData2, }, showDataPointLabel: true, chartName: "chart name", type: "CHART_WIDGET", chartType: "AREA_CHART", customEChartConfig: {}, customFusionChartConfig: { type: "type", dataSource: undefined }, hasOnDataPointClick: true, isVisible: true, isLoading: false, setAdaptiveYMin: false, labelOrientation: LabelOrientation.AUTO, onDataPointClick: "", widgetId: "widgetID", xAxisName: "xaxisname", yAxisName: "yaxisname", borderRadius: "1", boxShadow: "1", primaryColor: "primarycolor", fontFamily: "fontfamily", dimensions: { componentWidth: 11, componentHeight: 11 }, parentColumnSpace: 1, parentRowSpace: 1, topRow: 0, bottomRow: 0, leftColumn: 0, rightColumn: 0, widgetName: "widgetName", version: 1, renderMode: RenderModes.CANVAS, }; it("returns zero errors when errors field is undefined", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.errors = undefined; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); it("returns zero errors when errors field is null", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.errors = null; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); describe("when errors are present in non data fields", () => { const props = JSON.parse(JSON.stringify(defaultProps)); it("returns errors when chart type is basic echarts", () => { props.chartType = "LINE_CHART"; const nonDataFieldPropertyPath = "accentColor"; const widgetError: WidgetError = { type: "property", path: nonDataFieldPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(1); expect(syntaxErrors[0].name).toEqual("ErrorName"); }); it("returns errors when chart type is custom fusion charts", () => { props.chartType = "CUSTOM_FUSION_CHART"; const nonDataFieldPropertyPath = "accentColor"; const widgetError: WidgetError = { type: "property", path: nonDataFieldPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(1); expect(syntaxErrors[0].name).toEqual("ErrorName"); }); it("returns errors when chart type is basic echarts", () => { props.chartType = "CUSTOM_ECHART"; const nonDataFieldPropertyPath = "accentColor"; const widgetError: WidgetError = { type: "property", path: nonDataFieldPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(1); expect(syntaxErrors[0].name).toEqual("ErrorName"); }); }); describe("when errors are present in data fields", () => { describe("When chart type is Custom Fusion Charts", () => { const customFusionChartProps = JSON.parse(JSON.stringify(defaultProps)); customFusionChartProps.chartType = "CUSTOM_FUSION_CHART"; it("returns errors when errors are present in customFusionCharts", () => { const props = JSON.parse(JSON.stringify(customFusionChartProps)); const customFusionChartDataFieldPropertyPath = "customFusionChartConfig"; const widgetError: WidgetError = { type: "property", path: customFusionChartDataFieldPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(1); expect(syntaxErrors[0].name).toEqual("ErrorName"); }); it("doesn't return errors when errors are present in basic echarts data field", () => { const props = JSON.parse(JSON.stringify(customFusionChartProps)); const basicEChartsDataFieldPropertyPath = "chartData"; const widgetError: WidgetError = { type: "property", path: basicEChartsDataFieldPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); it("doesn't return errors when errors are present in custom echarts data field", () => { const props = JSON.parse(JSON.stringify(customFusionChartProps)); const customEChartsDataFieldPropertyPath = "customEChartConfig"; const widgetError: WidgetError = { type: "property", path: customEChartsDataFieldPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); }); describe("When chart type is basic ECharts", () => { const basicEChartsProps = JSON.parse(JSON.stringify(defaultProps)); basicEChartsProps.chartType = "LINE_CHART"; it("returns errors when errors are present in chart data field", () => { const props = JSON.parse(JSON.stringify(basicEChartsProps)); const echartDataPropertyPath = "chartData"; const widgetError: WidgetError = { type: "property", path: echartDataPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(1); expect(syntaxErrors[0].name).toEqual("ErrorName"); }); it("doesn't return errors when errors are present in custom fusion chart", () => { const props = JSON.parse(JSON.stringify(basicEChartsProps)); const customFusionChartDataPropertyPath = "customFusionChartConfig"; const widgetError: WidgetError = { type: "property", path: customFusionChartDataPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); it("doesn't return errors when errors are present in custom echarts", () => { const props = JSON.parse(JSON.stringify(basicEChartsProps)); const customEChartsDataPropertyPath = "customEChartConfig"; const widgetError: WidgetError = { type: "property", path: customEChartsDataPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); describe("when chart type is PIE CHART", () => { const pieChartProps = JSON.parse(JSON.stringify(basicEChartsProps)); pieChartProps.chartType = "PIE_CHART"; it("returns error if there is syntax error in first series data", () => { const props = JSON.parse(JSON.stringify(pieChartProps)); const firstSeriesDataPath = "chartData.seriesID1.data"; const widgetError: WidgetError = { type: "property", path: firstSeriesDataPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(1); expect(syntaxErrors[0].name).toEqual("ErrorName"); }); it("doesn't return an error if there is syntax error in second series data", () => { const props = JSON.parse(JSON.stringify(pieChartProps)); const secondSeriesDataPath = "chartData.seriesID2.data"; const widgetError: WidgetError = { type: "property", path: secondSeriesDataPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); }); }); describe("When chart type is custom ECharts", () => { const customEChartsProps = JSON.parse(JSON.stringify(defaultProps)); customEChartsProps.chartType = "CUSTOM_ECHART"; it("returns errors when errors are present in custom Echart config field", () => { const props = JSON.parse(JSON.stringify(customEChartsProps)); const customEChartDataPropertyPath = "customEChartConfig"; const widgetError: WidgetError = { type: "property", path: customEChartDataPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(1); expect(syntaxErrors[0].name).toEqual("ErrorName"); }); it("doesn't return errors when errors are present in custom fusion chart", () => { const props = JSON.parse(JSON.stringify(customEChartsProps)); const customFusionChartDataPropertyPath = "customFusionChartConfig"; const widgetError: WidgetError = { type: "property", path: customFusionChartDataPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); it("doesn't return errors when errors are present in basic echarts data field", () => { const props = JSON.parse(JSON.stringify(customEChartsProps)); const basicEChartsDataFieldPropertyPath = "chartData"; const widgetError: WidgetError = { type: "property", path: basicEChartsDataFieldPropertyPath, name: "ErrorName", message: "ErrorMessage", }; props.errors = [widgetError]; const syntaxErrors = syntaxErrorsFromProps(props); expect(syntaxErrors.length).toEqual(0); }); }); }); });
1,590
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/widget/index.test.ts
import { emptyChartData } from "."; import ChartWidget from "."; import { LabelOrientation } from "../constants"; import type { ChartWidgetProps } from "."; import type { ChartData } from "../constants"; import { RenderModes } from "constants/WidgetConstants"; describe("emptyChartData", () => { const seriesData1: ChartData = { seriesName: "series1", data: [{ x: "x1", y: 1 }], color: "series1color", }; const seriesData2: ChartData = { seriesName: "series2", data: [{ x: "x1", y: 2 }], color: "series2color", }; const defaultProps: ChartWidgetProps = { allowScroll: true, showDataPointLabel: true, chartData: { seriesID1: seriesData1, seriesID2: seriesData2, }, chartName: "chart name", type: "CHART_WIDGET", chartType: "AREA_CHART", customEChartConfig: {}, customFusionChartConfig: { type: "type", dataSource: undefined }, hasOnDataPointClick: true, isVisible: true, isLoading: false, setAdaptiveYMin: false, labelOrientation: LabelOrientation.AUTO, onDataPointClick: "", widgetId: "widgetID", xAxisName: "xaxisname", yAxisName: "yaxisname", borderRadius: "1", boxShadow: "1", primaryColor: "primarycolor", fontFamily: "fontfamily", dimensions: { componentWidth: 11, componentHeight: 11 }, parentColumnSpace: 1, parentRowSpace: 1, topRow: 0, bottomRow: 0, leftColumn: 0, rightColumn: 0, widgetName: "widgetName", version: 1, renderMode: RenderModes.CANVAS, }; describe("font family", () => { expect(ChartWidget.fontFamily).toEqual("Nunito Sans"); }); describe("when chart type is basic ECharts", () => { const basicEChartProps = JSON.parse(JSON.stringify(defaultProps)); const basicEChartsType = "LINE_CHART"; basicEChartProps.chartType = basicEChartsType; it("returns true if each series data is absent", () => { const props = JSON.parse(JSON.stringify(basicEChartProps)); props.chartData.seriesID1 = { data: [] }; props.chartData.seriesID2 = { data: [] }; expect(emptyChartData(props)).toEqual(true); }); it("returns true if no series is present", () => { const props = JSON.parse(JSON.stringify(basicEChartProps)); props.chartData = {}; expect(emptyChartData(props)).toEqual(true); }); it("returns false if all series data are present", () => { const props = JSON.parse(JSON.stringify(basicEChartProps)); expect(emptyChartData(props)).toEqual(false); }); it("returns false if any of the series data is present", () => { const props = JSON.parse(JSON.stringify(basicEChartProps)); props.chartData.seriesID1 = { data: [] }; expect(emptyChartData(props)).toEqual(false); }); describe("when chart type is pie chart", () => { const pieChartProps = JSON.parse(JSON.stringify(defaultProps)); pieChartProps.chartType = "PIE_CHART"; it("returns true if first series data is empty", () => { const props = JSON.parse(JSON.stringify(pieChartProps)); props.chartData = { seriesID1: { data: [] } }; expect(emptyChartData(props)).toEqual(true); }); it("returns true if first series data is empty but second series data is present", () => { const props = JSON.parse(JSON.stringify(pieChartProps)); props.chartData.seriesID1 = { data: [] }; props.chartData.seriesID2 = { data: { x: "x1", y: 2 } }; expect(emptyChartData(props)).toEqual(true); }); }); }); describe("when chart type is custom fusion charts", () => { const customFusionChartProps = JSON.parse(JSON.stringify(defaultProps)); customFusionChartProps.chartType = "CUSTOM_FUSION_CHART"; it("returns true if customFusionChartConfig property is empty", () => { const props = JSON.parse(JSON.stringify(customFusionChartProps)); props.customFusionChartConfig = {}; expect(emptyChartData(props)).toEqual(true); }); it("returns false if customFusionChartConfig property is not empty", () => { const props = JSON.parse(JSON.stringify(customFusionChartProps)); props.chartType = "CUSTOM_FUSION_CHART"; props.customFusionChartConfig = { key: "value" }; expect(emptyChartData(props)).toEqual(false); }); }); describe("when chart type is custom echarts", () => { const customEChartsProps = JSON.parse(JSON.stringify(defaultProps)); customEChartsProps.chartType = "CUSTOM_ECHART"; it("returns true if customEChartConfig property is empty", () => { const props = JSON.parse(JSON.stringify(customEChartsProps)); props.customEChartConfig = {}; expect(emptyChartData(props)).toEqual(true); }); it("returns false if customEChartConfig property is not empty", () => { const props = JSON.parse(JSON.stringify(customEChartsProps)); props.customEChartConfig = { key: "value" }; expect(emptyChartData(props)).toEqual(false); }); }); describe("Widget Callouts", () => { ChartWidget.showCustomFusionChartDeprecationMessages = jest .fn() .mockReturnValue(true); it("returns custom fusion chart deprecation notice when chart type is custom fusion chart", () => { const props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "CUSTOM_FUSION_CHART"; const { getEditorCallouts } = ChartWidget.getMethods(); const messages = getEditorCallouts(props); expect(messages.length).toEqual(1); const deprecationMessage = messages[0]; expect(deprecationMessage.message).toEqual( "Custom Fusion Charts will stop being supported on March 1st 2024. Change the chart type to E-charts Custom to switch.", ); expect(deprecationMessage.links).toEqual([ { text: "Learn more", url: "https://docs.appsmith.com", }, ]); }); it("returns no callouts when chart type isn't custom fusion charts", () => { let props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "LINE_CHART"; const { getEditorCallouts } = ChartWidget.getMethods(); let messages = getEditorCallouts(props); expect(messages.length).toEqual(0); props = JSON.parse(JSON.stringify(defaultProps)); props.chartType = "CUSTOM_ECHART"; messages = getEditorCallouts(props); expect(messages.length).toEqual(0); }); }); });
1,592
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ChartWidget/widget/propertyConfig.test.ts
/* eslint-disable @typescript-eslint/no-namespace */ import { isString } from "lodash"; import { styleConfig, contentConfig } from "./propertyConfig"; import type { PropertyPaneControlConfig } from "constants/PropertyControlConstants"; const customEChartsEnabled = true; const showFusionChartDeprecationMessage = true; const config = [ ...contentConfig(customEChartsEnabled, showFusionChartDeprecationMessage), ...styleConfig, ]; declare global { namespace jest { interface Matchers<R> { toBePropertyPaneConfig(): R; } } } const validateControl = (control: Record<string, unknown>) => { if (typeof control !== "object") return false; const properties = [ "propertyName", "controlType", "isBindProperty", "isTriggerProperty", ]; properties.forEach((prop: string) => { if (!control.hasOwnProperty(prop)) { return false; } const value = control[prop]; if (isString(value) && value.length === 0) return false; }); return true; }; const validateSection = (section: Record<string, unknown>) => { if (typeof section !== "object") return false; if (!section.hasOwnProperty("sectionName")) return false; const name = section.sectionName; if ((name as string).length === 0) return false; if (section.children) { return (section.children as Array<Record<string, unknown>>).forEach( (child) => { if (!validateControl(child)) return false; }, ); } return true; }; expect.extend({ toBePropertyPaneConfig(received) { if (Array.isArray(received)) { let pass = true; received.forEach((section) => { if (!validateSection(section) && !validateControl(section)) pass = false; }); return { pass, message: () => "Expected value to be a property pane config internal", }; } return { pass: false, message: () => "Expected value to be a property pane config external", }; }, }); it("Validates Chart Widget's property config", () => { expect(config).toBePropertyPaneConfig(); }); describe("Validate Chart Widget's data property config", () => { const propertyConfigs: PropertyPaneControlConfig[] = config .map((sectionConfig) => sectionConfig.children) .flat(); it("Validates visibility of property fields customFusionChartConfig property is visible when chartType is CUSTOM_FUSION_CHART", () => { const visibleFields = propertyConfigs.filter((propertyConfig) => { return propertyConfig.propertyName == "customFusionChartConfig"; }); let hiddenFns = visibleFields.map( (config) => config.hidden, ) as unknown as ((props: any) => boolean)[]; expect(hiddenFns.length).toEqual(1); hiddenFns.forEach((fn) => { let result = true; result = fn({ chartType: "CUSTOM_FUSION_CHART" }); expect(result).toBeFalsy(); }); const hiddenFields = propertyConfigs.filter((propertyConfig) => { return [ "chartData", "allowScroll", "showDataPointLabel", "xAxisName", "yAxisName", "customEChartConfig", "labelOrientation", ].includes(propertyConfig.propertyName); }); hiddenFns = hiddenFields.map((config) => config.hidden) as unknown as (( props: any, ) => boolean)[]; expect(hiddenFns.length).toEqual(7); hiddenFns.forEach((fn) => { let result = true; result = fn({ chartType: "CUSTOM_FUSION_CHART" }); expect(result).toBeTruthy(); }); }); it("Validates visibility of property fields when chartType is CUSTOM_ECHART", () => { const visibleFields = propertyConfigs.filter((propertyConfig) => { return propertyConfig.propertyName == "customEChartConfig"; }); let hiddenFns = visibleFields.map( (config) => config.hidden, ) as unknown as ((props: any) => boolean)[]; expect(hiddenFns.length).toEqual(1); hiddenFns.forEach((fn) => { let result = true; result = fn({ chartType: "CUSTOM_ECHART" }); expect(result).toBeFalsy(); }); const hiddenFields = propertyConfigs.filter((propertyConfig) => { return [ "chartData", "allowScroll", "showDataPointLabel", "labelOrientation", "setAdaptiveYMin", "xAxisName", "yAxisName", "customFusionChartConfig", "title", ].includes(propertyConfig.propertyName); }); hiddenFns = hiddenFields.map((config) => config.hidden) as unknown as (( props: any, ) => boolean)[]; expect(hiddenFns.length).toEqual(8); hiddenFns.forEach((fn) => { let result = true; result = fn({ chartType: "CUSTOM_ECHART" }); expect(result).toBeTruthy(); }); }); it("Validates that axis labelOrientation is visible when chartType are LINE_CHART AREA_CHART COLUMN_CHART", () => { const allowedChartsTypes = ["LINE_CHART", "AREA_CHART", "COLUMN_CHART"]; const axisSection = config.find((c) => c.sectionName === "Axis"); const labelOrientationProperty = ( axisSection?.children as unknown as PropertyPaneControlConfig[] ).find((p) => p.propertyName === "labelOrientation"); allowedChartsTypes.forEach((chartType) => { const result = labelOrientationProperty?.hidden?.({ chartType }, ""); expect(result).toBeFalsy(); }); }); it("validates the datasource field is required in customFusionChartConfig", () => { const customFusionChartConfig = propertyConfigs.find((propertyConfig) => { return propertyConfig.propertyName == "customFusionChartConfig"; }); expect(customFusionChartConfig).not.toBeNull(); const dataSourceValidations = customFusionChartConfig?.validation?.params?.allowedKeys?.[1]; expect(dataSourceValidations?.params?.required).toEqual(true); expect(dataSourceValidations?.params?.ignoreCase).not.toBeNull(); expect(dataSourceValidations?.params?.ignoreCase).toEqual(false); }); it("validates that default value is present for chartData.data property", () => { const chartDataConfig = propertyConfigs.filter((propertyConfig) => { return propertyConfig.propertyName == "chartData"; })[0]; const chartDataConfigChildren: PropertyPaneControlConfig[] = (chartDataConfig.children ?? []) as PropertyPaneControlConfig[]; const chartDataDataConfig = chartDataConfigChildren.filter((config) => { return config.propertyName == "data"; })[0]; expect(chartDataDataConfig.validation?.params?.default).toEqual([]); }); it("validates that default value is present for customEChartConfig property", () => { const customEChartConfig = propertyConfigs.filter((propertyConfig) => { return propertyConfig.propertyName == "customEChartConfig"; })[0]; expect(customEChartConfig.validation?.params?.default).toEqual({}); }); it("validates that default value is present for custom charts property", () => { const customFusionChartConfig = propertyConfigs.filter((propertyConfig) => { return propertyConfig.propertyName == "customFusionChartConfig"; })[0]; expect(customFusionChartConfig.validation?.params?.default).toEqual({}); }); });
1,598
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CheckboxGroupWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CheckboxGroupWidget/widget/index.test.tsx
// eslint-disable-next-line // @ts-nocheck import { defaultSelectedValuesValidation } from "./"; describe("<CheckboxGroup />", () => { test("should return empty parsed array on null options", async () => { const result = defaultSelectedValuesValidation("", { options: null, }); expect(result).toStrictEqual({ isValid: true, parsed: [] }); }); test("should return parsed array on valid single default option as string", async () => { const result = defaultSelectedValuesValidation("blue", { options: [ { label: "blue", value: "blue", }, { label: "green", value: "green", }, ], }); expect(result).toStrictEqual({ isValid: true, parsed: ["blue"] }); }); test("should return parsed array on multiple default options as string ", async () => { const result = defaultSelectedValuesValidation("blue,green", { options: [ { label: "blue", value: "blue", }, { label: "green", value: "green", }, ], }); expect(result).toStrictEqual({ isValid: true, parsed: ["blue", "green"] }); }); test("should return parsed array on multiple default options as array ", async () => { const result = defaultSelectedValuesValidation(`["blue"]`, { options: [ { label: "blue", value: "blue", }, { label: "green", value: "green", }, ], }); expect(result).toStrictEqual({ isValid: true, parsed: ["blue"] }); }); });
1,616
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CodeScannerWidget/widget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CodeScannerWidget/widget/propertyConfig/contetConfig.test.ts
import type { PropertyPaneConfig, PropertyPaneControlConfig, } from "constants/PropertyControlConstants"; import { DefaultMobileCameraTypes } from "WidgetProvider/constants"; import contentConfig from "./contentConfig"; describe("codescanner property control", () => { const propertyConfigs = contentConfig .map((sectionConfig) => sectionConfig.children) .flat() as PropertyPaneControlConfig[]; const defaultCameraProperty = propertyConfigs.find( (propertyConfig) => propertyConfig.propertyName === "defaultCamera", ) as PropertyPaneConfig; it("validates the codescanner widget has a default camera property", () => { expect(defaultCameraProperty).not.toBeNull(); }); it("validates the options for default mobile camera property", () => { expect((defaultCameraProperty as any).options).toHaveLength(2); expect((defaultCameraProperty as any).options[0].value).toEqual( DefaultMobileCameraTypes.FRONT, ); expect((defaultCameraProperty as any).options[1].value).toEqual( DefaultMobileCameraTypes.BACK, ); }); it("validates the default mobile camera value to be back camera", () => { expect((defaultCameraProperty as any).defaultValue).toEqual( DefaultMobileCameraTypes.BACK, ); }); });
1,621
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ContainerWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ContainerWidget/widget/index.test.tsx
import GlobalHotKeys from "pages/Editor/GlobalHotKeys"; import React from "react"; import { MemoryRouter } from "react-router-dom"; import * as utilities from "selectors/editorSelectors"; import * as useDynamicAppLayoutHook from "utils/hooks/useDynamicAppLayout"; import * as useCanvasDraggingHook from "layoutSystems/fixedlayout/editor/FixedLayoutCanvasArenas/hooks/useCanvasDragging"; import store from "store"; import { buildChildren, widgetCanvasFactory, } from "test/factories/WidgetFactoryUtils"; import { sagasToRunForTests } from "test/sagas"; import { MockApplication, mockGetCanvasWidgetDsl } from "test/testCommon"; import { UpdateAppViewer, UpdatedEditor } from "test/testMockedWidgets"; import { render } from "test/testUtils"; import { generateReactKey } from "widgets/WidgetUtils"; describe("ContainerWidget tests", () => { const mockGetIsFetchingPage = jest.spyOn(utilities, "getIsFetchingPage"); const spyGetCanvasWidgetDsl = jest.spyOn(utilities, "getCanvasWidgetDsl"); jest .spyOn(useDynamicAppLayoutHook, "useDynamicAppLayout") .mockImplementation(() => true); const pushState = jest.spyOn(window.history, "pushState"); pushState.mockImplementation((state: any, title: any, url: any) => { window.document.title = title; window.location.pathname = url; }); it("Container widget should not invoke dragging and selection features in View mode", async () => { const containerId = generateReactKey(); const canvasId = generateReactKey(); const children: any = buildChildren([ { type: "CHECKBOX_WIDGET", parentId: canvasId, }, { type: "SWITCH_WIDGET", parentId: canvasId, }, { type: "BUTTON_WIDGET", parentId: canvasId, }, ]); const canvasWidget = buildChildren([ { type: "CANVAS_WIDGET", parentId: containerId, children, widgetId: canvasId, }, ]); const containerChildren: any = buildChildren([ { type: "CONTAINER_WIDGET", children: canvasWidget, widgetId: containerId, parentId: "0", }, ]); const dsl: any = widgetCanvasFactory.build({ children: containerChildren, }); spyGetCanvasWidgetDsl.mockImplementation(mockGetCanvasWidgetDsl); mockGetIsFetchingPage.mockImplementation(() => false); const spyUseCanvasDragging = jest .spyOn(useCanvasDraggingHook, "useCanvasDragging") .mockImplementation(() => ({ showCanvas: true, })); const appState = store.getState(); render( <MemoryRouter initialEntries={["/app/applicationSlug/pageSlug-page_id/"]}> <MockApplication> <GlobalHotKeys> <UpdateAppViewer dsl={dsl} /> </GlobalHotKeys> </MockApplication> </MemoryRouter>, { initialState: appState, sagasToRun: sagasToRunForTests }, ); expect(spyUseCanvasDragging).not.toHaveBeenCalled(); render( <MemoryRouter initialEntries={["/app/applicationSlug/pageSlug-page_id/edit"]} > <MockApplication> <GlobalHotKeys> <UpdatedEditor dsl={dsl} /> </GlobalHotKeys> </MockApplication> </MemoryRouter>, { initialState: appState, sagasToRun: sagasToRunForTests }, ); expect(spyUseCanvasDragging).toHaveBeenCalled(); }); });
1,627
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CurrencyInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CurrencyInputWidget/component/utilities.test.ts
import { getLocaleDecimalSeperator, getLocaleThousandSeparator, } from "widgets/WidgetUtils"; import { countryToFlag, formatCurrencyNumber, limitDecimalValue, parseLocaleFormattedStringToNumber, } from "./utilities"; let locale = "en-US"; jest.mock("utils/helpers", () => { const originalModule = jest.requireActual("utils/helpers"); return { __esModule: true, ...originalModule, getLocale: () => { return locale; }, }; }); describe("Utilities - ", () => { it("should test test countryToFlag", () => { [ ["IN", "🇮🇳"], ["in", "🇮🇳"], ["US", "🇺🇸"], ].forEach((d) => { expect(countryToFlag(d[0])).toBe(d[1]); }); String.fromCodePoint = undefined as any; [ ["IN", "IN"], ["in", "in"], ["US", "US"], ].forEach((d) => { expect(countryToFlag(d[0])).toBe(d[1]); }); }); it("should test formatCurrencyNumber", () => { //below values are in format of [no. of decimals, input, output] [ [0, "123", "123"], [1, "123", "123"], [2, "123", "123"], [0, "123.12", "123"], [1, "123.12", "123.1"], [2, "123.12", "123.12"], [2, "123456.12", "123,456.12"], [1, "123456.12", "123,456.1"], [0, "123456.12", "123,456"], [0, "12345678", "12,345,678"], [2, "12345678", "12,345,678"], [2, "0.22", "0.22"], [1, "0.22", "0.2"], [0, "0.22", "0"], [2, "0.22123123", "0.22"], [1, "0.22123123", "0.2"], [0, "0.22123123", "0"], [0, "4", "4"], [0, "4.9", "5"], [0, "4.2", "4"], [1, "4", "4"], [1, "4.9", "4.9"], [1, "4.99", "5.0"], [1, "4.10", "4.1"], [1, "4.12", "4.1"], [2, "4", "4"], [2, "4.90", "4.90"], [2, "4.9", "4.90"], [2, "4.99", "4.99"], [2, "4.10", "4.10"], [2, "4.1", "4.10"], [2, "4.11", "4.11"], [2, "4.119", "4.12"], [2, "4.111", "4.11"], [2, "4.999", "5.00"], ].forEach((d) => { expect(formatCurrencyNumber(d[0] as number, d[1] as string)).toBe(d[2]); }); }); it("should test limitDecimalValue", () => { [ [0, "123.12", "123"], [1, "123.12", "123.1"], [2, "123.12", "123.12"], [2, "123456.12", "123456.12"], [1, "123456.12", "123456.1"], [0, "123456.12", "123456"], [2, "0.22", "0.22"], [1, "0.22", "0.2"], [0, "0.22", "0"], [2, "0.22123123", "0.22"], [1, "0.22123123", "0.2"], [0, "0.22123123", "0"], ].forEach((d) => { expect(limitDecimalValue(d[0] as number, d[1] as string)).toBe(d[2]); }); }); it("should test getLocaleDecimalSeperator", () => { expect(getLocaleDecimalSeperator()).toBe("."); locale = "en-IN"; expect(getLocaleDecimalSeperator()).toBe("."); locale = "hr-HR"; expect(getLocaleDecimalSeperator()).toBe(","); }); it("should test getLocaleThousandSeparator", () => { locale = "en-US"; expect(getLocaleThousandSeparator()).toBe(","); locale = "en-IN"; expect(getLocaleThousandSeparator()).toBe(","); locale = "hr-HR"; expect(getLocaleThousandSeparator()).toBe("."); }); it("shoud test parseLocaleFormattedStringToNumber", () => { locale = "en-US"; [ ["123", 123], ["123.12", 123.12], ["123,456.12", 123456.12], ["123,456,789.12", 123456789.12], ["0.22", 0.22], ["0.22123123", 0.22123123], ].forEach((d) => { expect(parseLocaleFormattedStringToNumber(d[0] as string)).toBe(d[1]); }); locale = "hr-HR"; [ ["123", 123], ["123,12", 123.12], ["123.456,12", 123456.12], ["123.456.789,12", 123456789.12], ["0,22", 0.22], ["0,22123123", 0.22123123], ].forEach((d) => { expect(parseLocaleFormattedStringToNumber(d[0] as string)).toBe(d[1]); }); }); });
1,630
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CurrencyInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CurrencyInputWidget/widget/derived.test.ts
import derivedProperty from "./derived"; describe("Derived property - ", () => { describe("isValid property", () => { it("should test isRequired", () => { let isValid = derivedProperty.isValid({ text: undefined, isRequired: false, }); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid({ text: undefined, isRequired: true, }); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid({ value: 100, text: "100", isRequired: true, }); expect(isValid).toBeTruthy(); }); it("should test validation", () => { let isValid = derivedProperty.isValid({ value: 100, text: "100", validation: false, }); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid({ value: 100, text: "100", validation: true, }); expect(isValid).toBeTruthy(); }); it("should test regex validation", () => { let isValid = derivedProperty.isValid({ value: 100, text: "100", regex: "^100$", }); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid({ value: 101, text: "101", regex: "^100$", }); expect(isValid).toBeFalsy(); }); }); });
1,631
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CurrencyInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/CurrencyInputWidget/widget/index.test.tsx
import type { CurrencyInputWidgetProps } from "./index"; import { defaultValueValidation } from "./index"; import _ from "lodash"; describe("defaultValueValidation", () => { let result: any; it("should validate defaulttext", () => { result = defaultValueValidation("100", {} as CurrencyInputWidgetProps, _); expect(result).toEqual({ isValid: true, parsed: "100", messages: [{ name: "", message: "" }], }); result = defaultValueValidation("test", {} as CurrencyInputWidgetProps, _); expect(result).toEqual({ isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: "This value must be number", }, ], }); result = defaultValueValidation("", {} as CurrencyInputWidgetProps, _); expect(result).toEqual({ isValid: true, parsed: undefined, messages: [{ name: "", message: "" }], }); }); it("should validate defaulttext with object value", () => { const value = {}; result = defaultValueValidation(value, {} as CurrencyInputWidgetProps, _); expect(result).toEqual({ isValid: false, parsed: JSON.stringify(value, null, 2), messages: [ { name: "TypeError", message: "This value must be number", }, ], }); }); });
1,642
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DatePickerWidget2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DatePickerWidget2/component/Date.test.ts
import moment from "moment"; import { DateFormatOptions } from "../widget/constants"; import { parseDate } from "./utils"; describe("DatePickerWidget", () => { it("should parse date strings correctly according to date formats", () => { const testDate = new Date(2000000000000); // let's enter into the future DateFormatOptions.forEach((format) => { const testDateStr = moment(testDate).format(format.value); const parsedDate = parseDate(testDateStr, format.value); const receivedDate = moment(testDateStr, format.value).toDate(); expect(parsedDate.getFullYear()).toBe(receivedDate.getFullYear()); expect(parsedDate.getUTCMonth()).toBe(receivedDate.getUTCMonth()); expect(parsedDate.getDate()).toBe(receivedDate.getDate()); expect(parsedDate.getHours()).toBe(receivedDate.getHours()); expect(parsedDate.getMinutes()).toBe(receivedDate.getMinutes()); expect(parsedDate.getSeconds()).toBe(receivedDate.getSeconds()); expect(parsedDate.getMilliseconds()).toBe(receivedDate.getMilliseconds()); }); }); });
1,654
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DividerWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DividerWidget/widget/index.test.tsx
import { render } from "@testing-library/react"; import { dark, theme } from "constants/DefaultTheme"; import React from "react"; import { Provider } from "react-redux"; import configureStore from "redux-mock-store"; import { ThemeProvider } from "styled-components"; import type { DividerWidgetProps } from "./"; import DividerWidget from "./"; describe("<DividerWidget />", () => { const initialState = { ui: { appSettingsPane: { isOpen: false, }, users: { featureFlag: { data: {}, }, }, widgetDragResize: { lastSelectedWidget: "Widget1", selectedWidgets: ["Widget1"], }, propertyPane: { isVisible: true, widgetId: "Widget1", }, debugger: { errors: {}, }, editor: { isPreviewMode: false, }, widgetReflow: { enableReflow: true, }, autoHeightUI: { isAutoHeightWithLimitsChanging: false, }, mainCanvas: { width: 1159, }, canvasSelection: { isDraggingForSelection: false, }, }, entities: { canvasWidgets: {}, app: { mode: "canvas" } }, }; function renderDividerWidget(props: Partial<DividerWidgetProps> = {}) { const defaultProps: DividerWidgetProps = { orientation: "horizontal", capType: "nc", capSide: -1, strokeStyle: "solid", dividerColor: "black", thickness: 2, widgetId: "Widget1", type: "DIVIDER_WIDGET", widgetName: "Divider 1", parentId: "Container1", renderMode: "CANVAS", parentColumnSpace: 2, parentRowSpace: 3, leftColumn: 2, rightColumn: 4, topRow: 1, bottomRow: 2, isLoading: false, version: 1, disablePropertyPane: false, ...props, }; // Mock store to bypass the error of react-redux const store = configureStore()(initialState); return render( <Provider store={store}> <ThemeProvider theme={{ ...theme, colors: { ...theme.colors, ...dark } }} > <DividerWidget {...defaultProps} /> </ThemeProvider> </Provider>, ); } test("should render Divider widget horizontal by default", async () => { const { queryByTestId } = renderDividerWidget(); expect(queryByTestId("dividerHorizontal")).toBeTruthy(); }); test("should render Divider vertical", async () => { const { queryByTestId } = renderDividerWidget({ orientation: "vertical" }); expect(queryByTestId("dividerVertical")).toBeTruthy(); }); });
1,660
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DocumentViewerWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DocumentViewerWidget/component/ExcelDataParser.test.ts
import type { RawSheetData, ExcelData, HeaderCell } from "./ExcelDataParser"; import { parseExcelData } from "./ExcelDataParser"; describe("parseExcelData", () => { describe("Header", () => { it("returns a list of header columns using the data", () => { const data: RawSheetData = [ ["r0c0", "r0c1", "r0c2"], ["r1c1", "r1c1", "r1c2"], ]; const expectedHeader: HeaderCell[] = [ { Header: "A", accessor: "A", }, { Header: "B", accessor: "B", }, { Header: "C", accessor: "C", }, ]; const output = parseExcelData(data); expect(output.headers).toEqual(expectedHeader); }); it("includes data with maximum number of elements for calculation of headers, not just first row", () => { const data: RawSheetData = [["r0c0"], ["r1c1", "r1c1", "r1c2"]]; const expectedHeaders = [ { Header: "A", accessor: "A", }, { Header: "B", accessor: "B", }, { Header: "C", accessor: "C", }, ]; const output = parseExcelData(data); expect(output.headers).toEqual(expectedHeaders); }); it("includes headers for empty values", () => { const data: RawSheetData = [["r0c0"], ["r1c1", "r1c1", , "r1c3"]]; const expectedHeaders = [ { Header: "A", accessor: "A", }, { Header: "B", accessor: "B", }, { Header: "C", accessor: "C", }, { Header: "D", accessor: "D", }, ]; const output = parseExcelData(data); expect(output.headers).toEqual(expectedHeaders); }); it("calculates double letter headers if number of items in data is more than 26", () => { const lastRowData = [["r26c0", "r26c1"]]; let data: RawSheetData = [ ["r0c0"], ["r1c0"], ["r2c0"], ["r3c0"], ["r4c0"], ["r5c0"], ["r6c0"], ["r7c0"], ["r8c0"], ["r9c0"], ["r10c0"], ["r11c0"], ["r12c0"], ["r13c0"], ["r14c0"], ["r15c0"], ["r16c0"], ["r17c0"], ["r18c0"], ["r19c0"], ["r20c0"], ["r21c0"], ["r22c0"], ["r23c0"], ["r24c0"], ["r25c0"], ]; data = [...data, ...lastRowData]; const expectedHeaders = [ { Header: "A", accessor: "A", }, { Header: "B", accessor: "B", }, ]; const output = parseExcelData(data); expect(output.headers).toEqual(expectedHeaders); }); }); describe("Body", () => { it("parses raw data into excel data format", () => { const data = [["r0c0"], ["r1c0", "r1c1"], ["r2c0", "r2c1", "r2c2"]]; const expectedBody = [ { A: "r0c0" }, { A: "r1c0", B: "r1c1" }, { A: "r2c0", B: "r2c1", C: "r2c2" }, ]; const output = parseExcelData(data); expect(output.body).toEqual(expectedBody); }); it("includes empty values into excel data format", () => { const data = [["r0c0"], ["r1c0", "r1c1"], ["r2c0", "r2c1", , "r2c3"]]; const expectedBody = [ { A: "r0c0" }, { A: "r1c0", B: "r1c1" }, { A: "r2c0", B: "r2c1", C: undefined, D: "r2c3" }, ]; const output = parseExcelData(data); expect(output.body).toEqual(expectedBody); }); }); describe("Output", () => { it("returns correctly parsed header and body together", () => { const data: RawSheetData = [ ["r0c0", "r0c1", "r0c2"], ["r1c0", "r1c1", "r1c2"], ]; const expectedOutput: ExcelData = { headers: [ { Header: "A", accessor: "A", }, { Header: "B", accessor: "B", }, { Header: "C", accessor: "C", }, ], body: [ { A: "r0c0", B: "r0c1", C: "r0c2" }, { A: "r1c0", B: "r1c1", C: "r1c2" }, ], }; const output = parseExcelData(data); expect(output).toEqual(expectedOutput); }); it("returns correctly parsed header and body together for empty values", () => { const data: RawSheetData = [ ["r0c0", "r0c1", "r0c2"], ["r1c0", "r1c1", "r1c2", , , "r1c5"], ]; const expectedOutput: ExcelData = { headers: [ { Header: "A", accessor: "A", }, { Header: "B", accessor: "B", }, { Header: "C", accessor: "C", }, { Header: "D", accessor: "D", }, { Header: "E", accessor: "E", }, { Header: "F", accessor: "F", }, ], body: [ { A: "r0c0", B: "r0c1", C: "r0c2" }, { A: "r1c0", B: "r1c1", C: "r1c2", D: undefined, E: undefined, F: "r1c5", }, ], }; const output = parseExcelData(data); expect(output).toEqual(expectedOutput); }); }); });
1,663
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DocumentViewerWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DocumentViewerWidget/component/index.test.tsx
import { getDocViewerConfigs } from "widgets/DocumentViewerWidget/component"; import { Renderers } from "../constants"; describe("validate document viewer url", () => { it("validate correct config should return for extension based urls", () => { const input = [ "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.docx", "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.odt", "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.rtf", "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.pdf", "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.txt", ]; const expected = [ { url: "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.docx", viewer: "office", errorMessage: "", renderer: Renderers.DOCUMENT_VIEWER, }, { url: "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.odt", viewer: "url", errorMessage: "Current file type is not supported", renderer: Renderers.ERROR, }, { url: "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.rtf", viewer: "url", errorMessage: "Current file type is not supported", renderer: Renderers.ERROR, }, { url: "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.pdf", viewer: "url", errorMessage: "", renderer: Renderers.DOCUMENT_VIEWER, }, { url: "https://roteemealplancover.s3.ap-south-1.amazonaws.com/sample/Project+proposal.txt", viewer: "url", errorMessage: "", renderer: Renderers.DOCUMENT_VIEWER, }, ]; for (let index = 0; index < input.length; index++) { const result = getDocViewerConfigs(input[index]); expect(result).toStrictEqual(expected[index]); } }); it("validate errorMessage should return for empty url", () => { const input = ""; const result = getDocViewerConfigs(input); expect(result).toStrictEqual({ url: "", viewer: "url", errorMessage: "No document url provided for viewer", renderer: Renderers.ERROR, }); }); });
1,665
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DocumentViewerWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DocumentViewerWidget/widget/index.test.tsx
import { documentUrlValidation } from "."; describe("validate propertypane input : docUrl", () => { it("validation for empty or space value", () => { const input1 = ""; const expected1 = { isValid: true, parsed: "", messages: [{ name: "", message: "" }], }; const result = documentUrlValidation(input1); expect(result).toStrictEqual(expected1); const input2 = "https: //www.example.com"; const expected2 = { isValid: false, parsed: "", messages: [ { name: "ValidationError", message: "Provided URL / Base64 is invalid.", }, ], }; const result1 = documentUrlValidation(input2); expect(result1).toStrictEqual(expected2); const input3 = "https://www.exam ple.com"; const expected3 = { isValid: false, parsed: "", messages: [ { name: "ValidationError", message: "Provided URL / Base64 is invalid.", }, ], }; const result2 = documentUrlValidation(input3); expect(result2).toStrictEqual(expected3); const input4 = "https://examplecom"; const expected4 = { isValid: false, parsed: "", messages: [ { name: "ValidationError", message: "Provided URL / Base64 is invalid.", }, ], }; const result3 = documentUrlValidation(input4); expect(result3).toStrictEqual(expected4); const input6 = "://www.appsmith.com/docs/sample.pdf"; const expected6 = { isValid: false, parsed: "", messages: [ { name: "ValidationError", message: "Provided URL / Base64 is invalid.", }, ], }; const result5 = documentUrlValidation(input6); expect(result5).toStrictEqual(expected6); }); it("validation for invalid url or base64 value", () => { const input1 = "htt"; const expected1 = { isValid: false, parsed: "", messages: [ { name: "ValidationError", message: "Provided URL / Base64 is invalid.", }, ], }; const result1 = documentUrlValidation(input1); expect(result1).toStrictEqual(expected1); const input2 = "data:application/pdf;base64"; const expected2 = { isValid: false, parsed: "", messages: [ { name: "ValidationError", message: "Provided URL / Base64 is invalid.", }, ], }; const result2 = documentUrlValidation(input2); expect(result2).toStrictEqual(expected2); }); it("validation for valid url or base64 value", () => { const input1 = "https://www.example.com"; const expected1 = { isValid: true, parsed: "https://www.example.com/", }; const result1 = documentUrlValidation(input1); expect(result1).toStrictEqual(expected1); const input2 = "data:application/pdf;base64,JVBERi0xLjIgCjkgMCBvYmoKPDwKPj4Kc3RyZWFtCkJULyAzMiBUZiggIFlPVVIgVEVYVCBIRVJFICAgKScgRVQKZW5kc3RyZWFtCmVuZG9iago0IDAgb2JqCjw8Ci9UeXBlIC9QYWdlCi9QYXJlbnQgNSAwIFIKL0NvbnRlbnRzIDkgMCBSCj4+CmVuZG9iago1IDAgb2JqCjw8Ci9LaWRzIFs0IDAgUiBdCi9Db3VudCAxCi9UeXBlIC9QYWdlcwovTWVkaWFCb3ggWyAwIDAgMjUwIDUwIF0KPj4KZW5kb2JqCjMgMCBvYmoKPDwKL1BhZ2VzIDUgMCBSCi9UeXBlIC9DYXRhbG9nCj4+CmVuZG9iagp0cmFpbGVyCjw8Ci9Sb290IDMgMCBSCj4+CiUlRU9G"; const expected2 = { isValid: true, parsed: input2, }; const result2 = documentUrlValidation(input2); expect(result2).toStrictEqual(expected2); const input3 = "https:www.appsmith.com/docs/sample.pdf"; const expected3 = { isValid: true, parsed: "https://www.appsmith.com/docs/sample.pdf", }; const result3 = documentUrlValidation(input3); expect(result3).toStrictEqual(expected3); const input4 = "https://www.apsmith.com/docs/sample"; const expected4 = { isValid: true, parsed: "https://www.apsmith.com/docs/sample", }; const result4 = documentUrlValidation(input4); expect(result4).toStrictEqual(expected4); const input5 = "www.learningcontainer.com/wp-content/uploads/2019/09/sample-pdf-file.pdf"; const expected5 = { isValid: true, parsed: "https://www.learningcontainer.com/wp-content/uploads/2019/09/sample-pdf-file.pdf", }; const result5 = documentUrlValidation(input5); expect(result5).toStrictEqual(expected5); }); });
1,672
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DropdownWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/DropdownWidget/widget/index.test.tsx
import { fireEvent, render, screen } from "@testing-library/react"; import { dark, theme } from "constants/DefaultTheme"; import React from "react"; import { Provider } from "react-redux"; import configureStore from "redux-mock-store"; import { ThemeProvider } from "styled-components"; import type { DropdownWidgetProps } from "./"; import DropdownWidget from "./"; import "@testing-library/jest-dom"; import { RenderModes } from "constants/WidgetConstants"; describe("<DropdownWidget />", () => { const initialState = { ui: { appSettingsPane: { isOpen: false, }, widgetDragResize: { lastSelectedWidget: "Widget1", selectedWidgets: ["Widget1"], }, users: { featureFlag: { data: {}, }, }, propertyPane: { isVisible: true, widgetId: "Widget1", }, debugger: { errors: {}, }, editor: { isPreviewMode: false, }, widgetReflow: { enableReflow: true, }, autoHeightUI: { isAutoHeightWithLimitsChanging: false, }, mainCanvas: { width: 1159, }, canvasSelection: { isDraggingForSelection: false, }, }, entities: { canvasWidgets: {}, app: { mode: "canvas" } }, }; function renderDropdownWidget(props: DropdownWidgetProps) { // Mock store to bypass the error of react-redux const store = configureStore()(initialState); return render( <Provider store={store}> <ThemeProvider theme={{ ...theme, colors: { ...theme.colors, ...dark } }} > <DropdownWidget {...props} /> </ThemeProvider> </Provider>, ); } test("should not render dropdown wrapper if options are empty", async () => { const mockDataWithEmptyOptions = { widgetId: "Widget1", type: "DIVIDER_WIDGET", widgetName: "Divider 1", renderMode: RenderModes.CANVAS, parentColumnSpace: 2, parentRowSpace: 3, leftColumn: 2, rightColumn: 4, topRow: 1, bottomRow: 2, isLoading: false, version: 1, selectedOption: { label: "", value: "" }, options: [], onOptionChange: "mock-option-change", isRequired: false, isFilterable: false, defaultValue: "mock-label-1", selectedOptionLabel: "mock-label-1", serverSideFiltering: false, onFilterUpdate: "mock-update", updateWidgetMetaProperty: jest.fn(), }; // @ts-expect-error: type mismatch renderDropdownWidget(mockDataWithEmptyOptions); const selectElement = screen.getByText("-- Select --"); fireEvent.click(selectElement); expect(screen.getByText("No Results Found")).toBeInTheDocument(); }); });
1,685
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/FilePickerWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/FilePickerWidgetV2/widget/FileParser.test.tsx
import FileDataTypes from "../constants"; import parseFileData from "./FileParser"; import fs from "fs"; import path from "path"; describe("File parser formats differenty file types correctly", () => { it("parses csv file correclty", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/Test_csv.csv", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = await parseFileData( blob, FileDataTypes.Array, "text/csv", "csv", false, ); const expectedResult = [ { "Data Id": "hsa-miR-942-5p", String: "Blue", Number: "23.788", Boolean: "TRUE", Empty: "", Date: "Wednesday, 20 January 1999", }, { "Data Id": "hsa-miR-943", String: "Black", Number: "1000", Boolean: "FALSE", Empty: "", Date: "2022-09-15", }, ]; expect(result).toStrictEqual(expectedResult); }); it("parses csv file correclty with dynamic bindig - Infer data types", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/Test_csv.csv", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = await parseFileData( blob, FileDataTypes.Array, "text/csv", "csv", true, ); const dateString = "2022-09-15"; const date = new Date(dateString); const timezoneOffset = date.getTimezoneOffset(); const offsetMilliseconds = timezoneOffset * 60 * 1000; const convertedDate = new Date(date.getTime() + offsetMilliseconds); const expectedResult = [ { "Data Id": "hsa-miR-942-5p", String: "Blue", Number: 23.788, Boolean: true, Empty: "", Date: "Wednesday, 20 January 1999", }, { "Data Id": "hsa-miR-943", String: "Black", Number: 1000, Boolean: false, Empty: "", Date: convertedDate, }, ]; expect(result).toStrictEqual(expectedResult); }); it("parses json file correclty", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/testdata.json", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = (await parseFileData( blob, FileDataTypes.Array, "application/json", "json", false, )) as Record<string, unknown>; expect(result["APPURL"]).toStrictEqual( "http://localhost:8081/app/app1/page1-63d38854252ca15b7ec9fabb", ); }); it("parses tsv file correctly", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/Sample.tsv", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = await parseFileData( blob, FileDataTypes.Array, "text/tab-separated-values", "tsv", false, ); const expectedResult = [ { "Last parameter": "12.45", "Other parameter": "123456", "Some parameter": "CONST", }, { "Last parameter": "Row2C3", "Other parameter": "Row2C2", "Some parameter": "Row2C1", }, ]; expect(result).toStrictEqual(expectedResult); }); it("parses xlsx file correctly", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/TestSpreadsheet.xlsx", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = await parseFileData( blob, FileDataTypes.Array, "openxmlformats-officedocument.spreadsheet", "xlsx", false, ); const expectedResult = [ { data: [ ["Column A", "Column B", "Column C"], ["r1a", "r1b", "r1c"], ["r2a", "r2b", "r2c"], ["r3a", "r3b", "r3c"], ], name: "Sheet1", }, ]; expect(result).toStrictEqual(expectedResult); }); it("parses xls file correctly", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/SampleXLS.xls", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = (await parseFileData( blob, FileDataTypes.Array, "", "xls", false, )) as Record<string, Record<string, unknown>[]>[]; const expectedFirstRow = [ 1, "Dulce", "Abril", "Female", "United States", 32, "15/10/2017", 1562, ]; expect(result[0]["name"]).toStrictEqual("Sheet1"); expect(result[0]["data"][1]).toStrictEqual(expectedFirstRow); }); it("parses text file correctly", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/testdata.json", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = await parseFileData(blob, FileDataTypes.Text, "", "", false); expect(typeof result).toStrictEqual("string"); expect(result).toContain( "http://localhost:8081/app/app1/page1-63d38854252ca15b7ec9fabb", ); }); it("parses binary file correctly", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/testdata.json", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = await parseFileData( blob, FileDataTypes.Binary, "", "", false, ); expect(typeof result).toStrictEqual("string"); expect(result).toContain( "http://localhost:8081/app/app1/page1-63d38854252ca15b7ec9fabb", ); }); it("parses base64 file correctly", async () => { const fixturePath = path.resolve( __dirname, "../../../../cypress/fixtures/testdata.json", ); const fileData = fs.readFileSync(fixturePath); const blob = new Blob([fileData]); const result = await parseFileData( blob, FileDataTypes.Base64, "", "", false, ); expect(typeof result).toStrictEqual("string"); expect(result).toContain( "data:application/octet-stream;base64,ewogICJiYXNlVXJsIjogImh0", ); }); });
1,723
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidget/component/index.test.tsx
import store from "store"; import React from "react"; import { ThemeProvider } from "styled-components"; import { theme } from "constants/DefaultTheme"; import InputComponent from "./"; import { Provider } from "react-redux"; import ReactDOM from "react-dom"; import { act } from "react-dom/test-utils"; import { noop } from "utils/AppsmithUtils"; let container: HTMLDivElement | null; beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container as Node); container = null; }); describe("<InputComponent />", () => { it("contains textarea with resize disabled", () => { act(() => { ReactDOM.render( <Provider store={store}> <ThemeProvider theme={theme}> {/* @ts-expect-error: type mismatch */} <InputComponent inputType="TEXT" isInvalid={false} isLoading={false} label="label" multiline onCurrencyTypeChange={noop} onFocusChange={noop} onValueChange={noop} showError={false} value="something" widgetId="24234r35" /> </ThemeProvider> </Provider>, container, ); }); const textarea = container?.querySelector("textarea"); const styles = textarea ? getComputedStyle(textarea) : { resize: "" }; expect(styles.resize).toEqual("none"); }); });
1,725
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidget/component/utilities.test.ts
import { formatCurrencyNumber, limitDecimalValue, getDecimalSeparator, getGroupSeparator, } from "./utilities"; describe("currency Number formating", () => { it("Without Decimal", () => { const response = formatCurrencyNumber(undefined, "1234560", "."); expect(response).toStrictEqual("1,234,560"); }); it("With Decimal", () => { const response = formatCurrencyNumber(2, "1234560.90", "."); expect(response).toStrictEqual("1,234,560.9"); }); it("With Decimal", () => { const response = formatCurrencyNumber(2, "1234560.9", "."); expect(response).toStrictEqual("1,234,560.9"); }); it("With Decimal", () => { const response = formatCurrencyNumber(2, "1234560.981", "."); expect(response).toStrictEqual("1,234,560.98"); }); }); describe("Limiting decimal Numbers ", () => { it("Without Decimal", () => { const response = limitDecimalValue(undefined, "1234560", ".", ","); expect(response).toStrictEqual("1234560"); }); it("With Decimal more than the limit", () => { const response = limitDecimalValue(2, "3456789.35444", ".", ","); expect(response).toStrictEqual("3456789.35"); }); }); describe("Decimal separator test", () => { it("For en-US locale", () => { const response = getDecimalSeparator("en-US"); expect(response).toEqual("."); }); it("For it (Italian) locale", () => { const response = getDecimalSeparator("it"); expect(response).toEqual(","); }); }); describe("Group separator test", () => { it("For en-US locale", () => { const response = getGroupSeparator("en-US"); expect(response).toEqual(","); }); it("For it (Italian) locale", () => { const response = getGroupSeparator("it"); expect(response).toEqual("."); }); });
1,727
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidget/widget/index.test.tsx
import type { InputWidgetProps } from "./index"; import { defaultValueValidation } from "./index"; import _ from "lodash"; describe("#defaultValueValidation", () => { const defaultInputWidgetProps: InputWidgetProps = { backgroundColor: "", borderRadius: "", bottomRow: 2, inputType: "NUMBER", inputValidators: [], isLoading: false, isValid: true, label: "", leftColumn: 0, parentColumnSpace: 71.75, parentRowSpace: 38, primaryColor: "", renderMode: "CANVAS", rightColumn: 100, text: "", topRow: 0, type: "INPUT_WIDGET", validation: true, version: 1, widgetId: "23424", widgetName: "input1", }; const inputs = [ "", " ", "0", "123", "-23", "0.000001", -23, 0, 100, "&*()(", "abcd", ]; const expectedOutputs = [ { isValid: true, parsed: undefined, messages: [{ name: "", message: "" }] }, { isValid: true, parsed: undefined, messages: [{ name: "", message: "" }] }, { isValid: true, parsed: 0, messages: [{ name: "", message: "" }] }, { isValid: true, parsed: 123, messages: [{ name: "", message: "" }] }, { isValid: true, parsed: -23, messages: [{ name: "", message: "" }] }, { isValid: true, parsed: 0.000001, messages: [{ name: "", message: "" }] }, { isValid: true, parsed: -23, messages: [{ name: "", message: "" }] }, { isValid: true, parsed: 0, messages: [{ name: "", message: "" }] }, { isValid: true, parsed: 100, messages: [{ name: "", message: "" }] }, { isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: "This value must be a number", }, ], }, { isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: "This value must be a number", }, ], }, ]; it("validates correctly for Number type", () => { const props = { ...defaultInputWidgetProps, }; inputs.forEach((input, index) => { const response = defaultValueValidation(input, props, _); expect(response).toStrictEqual(expectedOutputs[index]); }); }); it("validates correctly for Integer type", () => { const props = { ...defaultInputWidgetProps, inputType: "INTEGER", }; inputs.forEach((input, index) => { const response = defaultValueValidation(input, props, _); expect(response).toStrictEqual(expectedOutputs[index]); }); }); it("validates correctly for Currency type", () => { const props = { ...defaultInputWidgetProps, inputType: "CURRENCY", }; inputs.forEach((input, index) => { const response = defaultValueValidation(input, props, _); expect(response).toStrictEqual(expectedOutputs[index]); }); }); it("validates correctly for Phone Number type", () => { const props = { ...defaultInputWidgetProps, inputType: "PHONE_NUMBER", }; inputs.forEach((input, index) => { const response = defaultValueValidation(input, props, _); expect(response).toStrictEqual(expectedOutputs[index]); }); }); it("validates correctly for Number type with undefined value", () => { const props = { ...defaultInputWidgetProps, inputType: "NUMBER", }; const response = defaultValueValidation(undefined, props, _); expect(response).toStrictEqual({ isValid: true, parsed: undefined, messages: [{ name: "", message: "" }], }); }); });
1,732
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidgetV2/widget/Utilities.test.ts
import { InputTypes } from "widgets/BaseInputWidget/constants"; import { getParsedText } from "./Utilities"; describe("getParsedText", () => { it("should test with all possible values", () => { let text = getParsedText("test", InputTypes.TEXT); expect(text).toBe("test"); text = getParsedText("test1", InputTypes.PASSWORD); expect(text).toBe("test1"); text = getParsedText("[email protected]", InputTypes.EMAIL); expect(text).toBe("[email protected]"); text = getParsedText("", InputTypes.NUMBER); expect(text).toBe(null); text = getParsedText(undefined as unknown as string, InputTypes.NUMBER); expect(text).toBe(null); text = getParsedText(null as unknown as string, InputTypes.NUMBER); expect(text).toBe(null); text = getParsedText(1 as unknown as string, InputTypes.NUMBER); expect(text).toBe(1); text = getParsedText("1.01", InputTypes.NUMBER); expect(text).toBe(1.01); text = getParsedText("1.00", InputTypes.NUMBER); expect(text).toBe(1); }); });
1,735
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidgetV2/widget/derived.test.ts
import _ from "lodash"; import { InputTypes } from "widgets/BaseInputWidget/constants"; import derivedProperty from "./derived"; describe("Derived property - ", () => { describe("isValid property", () => { it("should test isRequired", () => { //Number input with required false and empty value let isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: undefined, isRequired: false, }, null, _, ); expect(isValid).toBeTruthy(); //Number input with required true and invalid value isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: "test", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Number input with required true and invalid value `null` isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: null, isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Number input with required true and invalid value `undefined` isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: undefined, isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Number input with required true and invalid value `""` isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Number input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: 1, isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); //Number input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: 1.1, isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); //Text input with required false and empty value isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, inputText: "", isRequired: false, }, null, _, ); expect(isValid).toBeTruthy(); //Text input with required true and invalid value isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, inputText: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Text input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, inputText: "test", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); //Email input with required false and empty value isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "", isRequired: false, }, null, _, ); expect(isValid).toBeTruthy(); //Email input with required true and invalid value isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Email input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "[email protected]", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); //Password input with required false and empty value isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, inputText: "", isRequired: false, }, null, _, ); expect(isValid).toBeTruthy(); //Password input with required true and invalid value isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, inputText: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Password input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, inputText: "admin", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("should test validation", () => { let isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, inputText: "test", isRequired: true, validation: false, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, inputText: "test", isRequired: true, validation: true, }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: 1, isRequired: true, validation: false, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: 1, isRequired: true, validation: true, }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "[email protected]", isRequired: true, validation: false, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "[email protected]", isRequired: true, validation: true, }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, inputText: "admin123", isRequired: true, validation: false, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, inputText: "admin123", isRequired: true, validation: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("should test regex validation", () => { let isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, inputText: "test", isRequired: true, regex: "^test$", }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, inputText: "test123", isRequired: true, regex: "^test$", }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: 1, isRequired: true, regex: "^1$", }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, inputText: 2, isRequired: true, regex: "^1$", }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "[email protected]", isRequired: true, regex: "^[email protected]$", }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "[email protected]", isRequired: true, regex: "^[email protected]$", }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, inputText: "admin123", isRequired: true, regex: "^admin123$", }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, inputText: "admin1234", isRequired: true, regex: "^admin123$", }, null, _, ); expect(isValid).toBeFalsy(); }); it("should test email type built in validation", () => { let isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "[email protected]", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "test", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, inputText: "[email protected]", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); }); });
1,736
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/InputWidgetV2/widget/index.test.tsx
import type { InputWidgetProps } from "./index"; import { defaultValueValidation, minValueValidation, maxValueValidation, } from "./index"; import _ from "lodash"; describe("defaultValueValidation", () => { let result: any; it("should validate defaulttext of text type", () => { result = defaultValueValidation( "text", { inputType: "TEXT" } as InputWidgetProps, _, ); expect(result).toEqual({ isValid: true, parsed: "text", messages: [{ name: "", message: "" }], }); result = defaultValueValidation( 1, { inputType: "TEXT" } as InputWidgetProps, _, ); expect(result).toEqual({ isValid: true, parsed: "1", messages: [{ name: "", message: "" }], }); }); it("should validate defaulttext of Number type", () => { result = defaultValueValidation( 1, { inputType: "NUMBER" } as InputWidgetProps, _, ); expect(result).toEqual({ isValid: true, parsed: 1, messages: [{ name: "", message: "" }], }); result = defaultValueValidation( "test", { inputType: "NUMBER" } as InputWidgetProps, _, ); expect(result).toEqual({ isValid: false, parsed: null, messages: [ { name: "TypeError", message: "This value must be number", }, ], }); }); it("should validate defaulttext of Email type", () => { result = defaultValueValidation( "[email protected]", { inputType: "EMAIL" } as InputWidgetProps, _, ); expect(result).toEqual({ isValid: true, parsed: "[email protected]", messages: [{ name: "", message: "" }], }); result = defaultValueValidation( 1, { inputType: "EMAIL" } as InputWidgetProps, _, ); expect(result).toEqual({ isValid: true, parsed: "1", messages: [{ name: "", message: "" }], }); }); it("should validate defaulttext of Password type", () => { result = defaultValueValidation( "admin123", { inputType: "PASSWORD" } as InputWidgetProps, _, ); expect(result).toEqual({ isValid: true, parsed: "admin123", messages: [{ name: "", message: "" }], }); result = defaultValueValidation( 1, { inputType: "PASSWORD" } as InputWidgetProps, _, ); expect(result).toEqual({ isValid: true, parsed: "1", messages: [{ name: "", message: "" }], }); }); it("should validate defaulttext with type missing", () => { result = defaultValueValidation( "admin123", { inputType: "" } as any as InputWidgetProps, _, ); expect(result).toEqual({ isValid: false, parsed: "", messages: [ { name: "TypeError", message: "This value must be string", }, ], }); }); it("should validate defaulttext with object value", () => { const value = {}; result = defaultValueValidation( value, { inputType: "" } as any as InputWidgetProps, _, ); expect(result).toEqual({ isValid: false, parsed: JSON.stringify(value, null, 2), messages: [ { name: "TypeError", message: "This value must be string", }, ], }); }); }); describe("minValueValidation - ", () => { it("should return true if minNum is empty", () => { expect( minValueValidation("", { maxNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeTruthy(); expect( minValueValidation(null, { maxNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeTruthy(); }); it("should return false if minNum is not a valid number", () => { expect( minValueValidation("test", { maxNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeFalsy(); }); it("should return false if minNum is not lesser than maxNum", () => { expect( minValueValidation("11", { maxNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeFalsy(); }); it("should return true if minNum is a finite number and lesser than maxNum", () => { expect( minValueValidation("1", { maxNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeTruthy(); }); }); describe("maxValueValidation - ", () => { it("should return true if maxNum is empty", () => { expect( maxValueValidation("", { minNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeTruthy(); expect( maxValueValidation(null, { minNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeTruthy(); }); it("should return false if maxNum is not a valid number", () => { expect( maxValueValidation("test", { minNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeFalsy(); }); it("should return false if maxNum is not greater than minNum", () => { expect( maxValueValidation("9", { minNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeFalsy(); }); it("should return true if maxNum is a finite number and lesser than minNum", () => { expect( maxValueValidation("18", { minNum: 10 } as InputWidgetProps, _ as any) .isValid, ).toBeTruthy(); }); });
1,741
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/helper.test.ts
import type { Schema, SchemaItem } from "./constants"; import { ARRAY_ITEM_KEY, DataType, FieldType, ROOT_SCHEMA_KEY, } from "./constants"; import { convertSchemaItemToFormData, countFields, mergeAllObjectsInAnArray, schemaItemDefaultValue, validateOptions, } from "./helper"; describe(".schemaItemDefaultValue", () => { it("returns array default value when sub array fields don't have default value", () => { const schemaItem = { accessor: "education", identifier: "education", originalIdentifier: "education", dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, isVisible: true, defaultValue: [ { college: "String field", graduationDate: "10/12/2021", }, ], children: { __array_item__: { identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, defaultValue: undefined, isVisible: true, children: { college: { label: "College", children: {}, isVisible: true, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, accessor: "college", identifier: "college", originalIdentifier: "college", }, graduationDate: { children: {}, isVisible: true, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.DATEPICKER, accessor: "graduationDate", identifier: "graduationDate", originalIdentifier: "graduationDate", }, }, }, }, } as unknown as SchemaItem; const expectedDefaultValue = [ { college: "String field", graduationDate: "10/12/2021", }, ]; const result = schemaItemDefaultValue(schemaItem, "identifier"); expect(result).toEqual(expectedDefaultValue); }); it("returns array default value when sub array fields don't have default value with accessor keys", () => { const schemaItem = { accessor: "education 1", identifier: "education", originalIdentifier: "education", dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, isVisible: true, defaultValue: [ { college: "String field", graduationDate: "10/12/2021", }, ], children: { __array_item__: { identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, defaultValue: undefined, isVisible: true, children: { college: { label: "College", children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, accessor: "graduating college", identifier: "college", originalIdentifier: "college", isVisible: true, }, graduationDate: { children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.DATEPICKER, accessor: "graduation date", identifier: "graduationDate", originalIdentifier: "graduationDate", isVisible: true, }, }, }, }, } as unknown as SchemaItem; const expectedDefaultValue = [ { "graduating college": "String field", "graduation date": "10/12/2021", }, ]; const result = schemaItemDefaultValue(schemaItem, "accessor"); expect(result).toEqual(expectedDefaultValue); }); it("returns merged default value when sub array fields have default value", () => { const schemaItem = { name: "education", accessor: "education", identifier: "education", originalIdentifier: "education", dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, isVisible: true, defaultValue: [ { college: "String field", graduationDate: "10/12/2021", }, ], children: { __array_item__: { accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, defaultValue: { college: "String field", graduationDate: "10/12/2021", }, isVisible: true, children: { college: { label: "College", children: {}, dataType: DataType.STRING, defaultValue: "Some college name", fieldType: FieldType.TEXT_INPUT, accessor: "college", identifier: "college", originalIdentifier: "college", isVisible: true, }, graduationDate: { children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.DATEPICKER, accessor: "graduationDate", identifier: "graduationDate", originalIdentifier: "graduationDate", isVisible: true, }, }, }, }, } as unknown as SchemaItem; const expectedDefaultValue = [ { college: "String field", graduationDate: "10/12/2021", }, ]; const result = schemaItemDefaultValue(schemaItem, "identifier"); expect(result).toEqual(expectedDefaultValue); }); it("returns merged default value when array field has default value more than one item", () => { const schemaItem = { name: "education", accessor: "education", identifier: "education", originalIdentifier: "education", dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, defaultValue: [ { college: "String field 1", graduationDate: "10/12/2021", }, { college: "String field 2", graduationDate: "30/12/2021", }, ], children: { __array_item__: { accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, isVisible: true, defaultValue: { college: "String field", graduationDate: "10/12/2021", }, children: { college: { label: "College", children: {}, dataType: DataType.STRING, defaultValue: "Some college name", fieldType: FieldType.TEXT_INPUT, accessor: "college", identifier: "college", originalIdentifier: "college", isVisible: true, }, graduationDate: { children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.DATEPICKER, accessor: "graduationDate", identifier: "graduationDate", originalIdentifier: "graduationDate", isVisible: true, }, }, }, }, } as unknown as SchemaItem; const expectedDefaultValue = [ { college: "String field 1", graduationDate: "10/12/2021", }, { college: "String field 2", graduationDate: "30/12/2021", }, ]; const result = schemaItemDefaultValue(schemaItem, "identifier"); expect(result).toEqual(expectedDefaultValue); }); it("returns only sub array fields default value, when array level default value is empty", () => { const schemaItem = { accessor: "education", identifier: "education", originalIdentifier: "education", dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, defaultValue: undefined, children: { __array_item__: { accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, defaultValue: undefined, children: { college: { label: "College", children: {}, dataType: DataType.STRING, defaultValue: "Some college name", fieldType: FieldType.TEXT_INPUT, accessor: "college", identifier: "college", originalIdentifier: "college", }, graduationDate: { children: {}, dataType: DataType.STRING, defaultValue: "10/10/2001", fieldType: FieldType.DATEPICKER, accessor: "graduationDate", identifier: "graduationDate", originalIdentifier: "graduationDate", }, }, }, }, } as unknown as SchemaItem; const expectedDefaultValue = [ { college: "Some college name", graduationDate: "10/10/2001", }, ]; const result = schemaItemDefaultValue(schemaItem, "identifier"); expect(result).toEqual(expectedDefaultValue); }); it("returns valid default value when non compliant keys in default value is present", () => { const schemaItem = { accessor: "education", identifier: "education", originalIdentifier: "education", dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, defaultValue: [ { "graduating college": "Some college name", "graduation date": "10/10/2001", }, ], children: { __array_item__: { accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, defaultValue: undefined, isVisible: true, children: { graduating_college: { label: "College", children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, accessor: "college", identifier: "graduating_college", originalIdentifier: "graduating college", isVisible: true, }, graduation_date: { children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.DATEPICKER, accessor: "newDate", identifier: "graduation_date", originalIdentifier: "graduation date", isVisible: true, }, }, }, }, } as unknown as SchemaItem; const expectedDefaultValue = [ { college: "Some college name", newDate: "10/10/2001", }, ]; const result = schemaItemDefaultValue(schemaItem, "identifier"); expect(result).toEqual(expectedDefaultValue); }); }); describe(".validateOptions", () => { it("returns values passed for valid values", () => { const inputAndExpectedOutput = [ [[""], true], [[0], true], [[true], true], [[false], true], [[{}, ""], false], [[{}, null], false], [[{}, undefined], false], [[{}, NaN], false], [["test", null], false], [["test", undefined], false], [["test", NaN], false], [["", null], false], [["", undefined], false], [["", NaN], false], [[0, null], false], [[0, undefined], false], [[0, NaN], false], [[1, null], false], [[1, undefined], false], [[1, NaN], false], [[{ label: "", value: "" }], true], [[{ label: "", value: "" }, { label: "" }], false], [{ label: "", value: "" }, false], ["label", false], [1, false], [null, false], [undefined, false], [NaN, false], [["one", "two"], true], [[1, 2], true], ]; inputAndExpectedOutput.forEach(([input, expectedOutput]) => { const result = validateOptions(input); expect(result).toEqual(expectedOutput); }); }); }); describe(".mergeAllObjectsInAnArray", () => { it("returns merged array", () => { const input = [ { number: 10, text: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj: { a: 10, c: 20, }, }, }, }, { number1: 10, text2: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj1: { a: 10, c: 20, }, }, }, }, ]; const expectedOutput = { number: 10, text: "text", number1: 10, text2: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj: { a: 10, c: 20, }, obj1: { a: 10, c: 20, }, }, }, }; const result = mergeAllObjectsInAnArray(input); expect(result).toEqual(expectedOutput); }); }); describe(".countFields", () => { it("return number of fields in an object", () => { const inputAndExpectedOutput = [ { input: { foo: { bar: 10 } }, expectedOutput: 2 }, { input: { foo: { bar: 10 }, arr: ["1", "2", "3"] }, expectedOutput: 3 }, { input: { foo: { bar: 10 }, arr: ["1", "2", "3"], arr1: [{ a: 10 }, { c: 10, d: { e: 20, k: ["a", "b"] } }], }, expectedOutput: 14, }, { input: { number: 10, text: "text", arr: { number: 10, text: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj: { a: 10, c: 20, }, }, }, }, arr2: ["1", "2"], arr1: [ { number: 10, text: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj: { a: 10, c: 20, }, }, }, }, { number1: 10, text2: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj1: { a: 10, c: 20, }, }, }, }, ], }, expectedOutput: 45, }, ]; inputAndExpectedOutput.forEach(({ expectedOutput, input }) => { const result = countFields(input); expect(result).toEqual(expectedOutput); }); }); }); describe(".convertSchemaItemToFormData", () => { const schema = { __root_schema__: { children: { customField1: { children: {}, dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "gender", identifier: "customField1", originalIdentifier: "customField1", isVisible: true, }, customField2: { children: {}, dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "age", identifier: "customField2", originalIdentifier: "customField2", isVisible: false, }, hiddenNonASCII: { isVisible: false, children: {}, dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "हिन्दि", identifier: "hiddenNonASCII", originalIdentifier: "हिन्दि", }, hiddenSmiley: { isVisible: false, children: {}, dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "😀", identifier: "hiddenSmiley", originalIdentifier: "😀", }, array: { children: { __array_item__: { children: { name: { dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "firstName", identifier: "name", originalIdentifier: "name", isVisible: true, }, date: { dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "graduationDate", identifier: "date", originalIdentifier: "date", isVisible: false, }, }, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, isVisible: true, }, }, dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, accessor: "students", identifier: "array", originalIdentifier: "array", isVisible: true, }, hiddenArray: { children: { __array_item__: { children: { name: { dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "firstName", identifier: "name", originalIdentifier: "name", isVisible: true, }, }, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, isVisible: true, }, }, dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, accessor: "testHiddenArray", identifier: "hiddenArray", originalIdentifier: "hiddenArray", isVisible: false, }, visibleObject: { children: { name: { dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "firstName", identifier: "name", originalIdentifier: "name", isVisible: true, }, date: { dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "graduationDate", identifier: "date", originalIdentifier: "date", isVisible: false, }, }, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, accessor: "testVisibleObject", identifier: "visibleObject", originalIdentifier: "visibleObject", isVisible: true, }, hiddenObject: { children: { name: { dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "firstName", identifier: "name", originalIdentifier: "name", isVisible: true, }, date: { dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, accessor: "graduationDate", identifier: "date", originalIdentifier: "date", isVisible: false, }, }, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, accessor: "testHiddenObject", identifier: "hiddenObject", originalIdentifier: "hiddenObject", isVisible: false, }, }, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, accessor: "", identifier: "", originalIdentifier: "", isVisible: true, }, } as unknown as Schema; it("replaces data with accessor keys to identifier keys", () => { const formData = { gender: "male", age: "20", students: [ { firstName: "test1", graduationDate: "10/12/2010" }, { firstName: "test2", graduationDate: "14/02/2010" }, ], testHiddenArray: [{ firstName: "test1" }, { firstName: "test2" }], testVisibleObject: { firstName: "test1", graduationDate: "10/12/2010" }, testHiddenObject: { firstName: "test1", graduationDate: "10/12/2010" }, }; const expectedOutput = { customField1: "male", array: [{ name: "test1" }, { name: "test2" }], visibleObject: { name: "test1" }, }; const result = convertSchemaItemToFormData( schema[ROOT_SCHEMA_KEY], formData, { fromId: "accessor", toId: "identifier" }, ); expect(result).toEqual(expectedOutput); }); it("replaces data with identifier keys to accessor keys", () => { const formData = { customField1: "male", customField2: "demo", array: [{ name: "test1" }, { name: "test2" }], hiddenArray: [{ name: "test1" }, { name: "test2" }], visibleObject: { name: "test1", date: "10/12/2010" }, hiddenObject: { name: "test1", date: "10/12/2010" }, }; const expectedOutput = { gender: "male", students: [{ firstName: "test1" }, { firstName: "test2" }], testVisibleObject: { firstName: "test1" }, }; const result = convertSchemaItemToFormData( schema[ROOT_SCHEMA_KEY], formData, { fromId: "identifier", toId: "accessor" }, ); expect(result).toEqual(expectedOutput); }); it("replaces data with identifier keys to accessor keys when keys are missing", () => { const formData = { customField1: "male", customField2: "demo1", customField3: "demo2", hiddenArray: [{ name: "test1" }, { name: "test2" }], visibleObject: { name: "test1", date: "10/12/2010" }, hiddenObject: { name: "test1", date: "10/12/2010" }, }; const expectedOutput = { gender: "male", testVisibleObject: { firstName: "test1" }, }; const result = convertSchemaItemToFormData( schema[ROOT_SCHEMA_KEY], formData, { fromId: "identifier", toId: "accessor" }, ); expect(result).toEqual(expectedOutput); }); it("replaces data with identifier keys to accessor keys when keys are undefined", () => { const formData = { customField1: "male", customField2: "demo", array: [{ name: "test1" }, { name: undefined }], hiddenArray: [{ name: "test1" }, { name: "test2" }], visibleObject: { name: "test1", date: "10/12/2010" }, hiddenObject: { name: "test1", date: "10/12/2010" }, }; const expectedOutput = { gender: "male", students: [{ firstName: "test1" }, { firstName: undefined }], testVisibleObject: { firstName: "test1" }, }; const result = convertSchemaItemToFormData( schema[ROOT_SCHEMA_KEY], formData, { fromId: "identifier", toId: "accessor" }, ); expect(result).toEqual(expectedOutput); }); it("set hidden form field value to available source field value when useSourceData is set to true", () => { const formData = { customField1: "male", customField2: "demo", array: [{ name: "test1" }, { name: null, date: "10/12/2010" }], hiddenArray: [{ name: "test1" }, { name: "test2" }], visibleObject: { name: "test1", date: "10/12/2010" }, hiddenObject: { name: "test1", date: "10/12/2010" }, }; const sourceData = { customField1: "soruceMale", customField2: "sourceDemo", array: [ { name: "sourceTest1" }, { name: "sourceTest2", date: "11/11/1111" }, ], hiddenArray: [{ name: "sourceTest1" }, { name: "sourceTest2" }], hiddenObject: { name: "sourceTest1" }, }; const expectedOutput = { gender: "male", age: "sourceDemo", students: [ { firstName: "test1" }, { firstName: null, graduationDate: "11/11/1111" }, ], testHiddenArray: [ { firstName: "sourceTest1" }, { firstName: "sourceTest2" }, ], testVisibleObject: { firstName: "test1" }, testHiddenObject: { firstName: "sourceTest1" }, }; const result = convertSchemaItemToFormData( schema[ROOT_SCHEMA_KEY], formData, { fromId: "identifier", toId: "accessor", sourceData: sourceData, useSourceData: true, }, ); expect(result).toEqual(expectedOutput); }); it("return expected result for non-ASCII source value when field is hidden and useSourceData is set to true", () => { const formData = { customField1: "male", array: [{ name: "test1" }, { name: null, date: "10/12/2010" }], hiddenNonASCII: "test", hiddenSmiley: "test 2", visibleObject: { name: "test1", date: "10/12/2010" }, }; const sourceData = { हिन्दि: "हिन्दि", "😀": "😀", }; const expectedOutput = { gender: "male", students: [{ firstName: "test1" }, { firstName: null }], हिन्दि: "हिन्दि", "😀": "😀", testVisibleObject: { firstName: "test1" }, }; const result = convertSchemaItemToFormData( schema[ROOT_SCHEMA_KEY], formData, { fromId: "identifier", toId: "accessor", sourceData: sourceData, useSourceData: true, }, ); expect(result).toEqual(expectedOutput); }); });
1,745
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/schemaParser.test.ts
import { get, set } from "lodash"; import { klona } from "klona"; import SchemaParser, { applyPositions, checkIfArrayAndSubDataTypeChanged, constructPlausibleObjectFromArray, dataTypeFor, fieldTypeFor, getKeysFromSchema, getSourceDataPathFromSchemaItemPath, getSourcePath, hasNullOrUndefined, normalizeArrayValue, subDataTypeFor, } from "./schemaParser"; import testData, { replaceBindingWithValue, schemaItemFactory, schemaItemStyles, } from "./schemaTestData"; import type { Schema, SchemaItem } from "./constants"; import { ARRAY_ITEM_KEY, DataType, FieldType, ROOT_SCHEMA_KEY, } from "./constants"; const widgetName = "JSONForm1"; const BASE_PATH = `schema.${ROOT_SCHEMA_KEY}`; describe("#parse", () => { it("returns a new schema for a valid data source", () => { const result = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: {}, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(result.schema).toEqual(testData.initialDataset.schemaOutput); }); it("returns an updated schema when a key removed from existing data source", () => { const expectedRemovedSchemaItems = [ `${BASE_PATH}.children.boolean`, `${BASE_PATH}.children.__`, ]; const expectedModifiedSchemaItems = {}; const { modifiedSchemaItems, removedSchemaItems, schema } = SchemaParser.parse(widgetName, { currSourceData: testData.withRemovedKeyFromInitialDataset.dataSource, schema: testData.initialDataset.schemaOutput, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(schema).toEqual( testData.withRemovedKeyFromInitialDataset.schemaOutput, ); expect(modifiedSchemaItems).toEqual(expectedModifiedSchemaItems); expect(removedSchemaItems).toEqual(expectedRemovedSchemaItems); }); it("returns an updated schema when new key added to existing data source", () => { const widgetName = "JSONForm1"; const expectedSchema = testData.withRemovedAddedKeyToInitialDataset.schemaOutput; const expectedRemovedSchemaItems = [ `${BASE_PATH}.children.boolean`, `${BASE_PATH}.children.__`, ]; const expectedModifiedSchemaItems = { [`${BASE_PATH}.children.gender`]: expectedSchema.__root_schema__.children.gender, }; const { modifiedSchemaItems, removedSchemaItems, schema } = SchemaParser.parse(widgetName, { currSourceData: testData.withRemovedAddedKeyToInitialDataset.dataSource, schema: testData.initialDataset.schemaOutput, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(schema).toEqual(expectedSchema); expect(modifiedSchemaItems).toEqual(expectedModifiedSchemaItems); expect(removedSchemaItems).toEqual(expectedRemovedSchemaItems); }); it("returns modified and removed keys for added/modified/removed keys in data source", () => { const initialSourceData = { name: "Test name", age: 20, dob: "10/12/2021", boolean: true, hobbies: ["travelling", "skating", "off-roading"], "%%": "%", education: [ { college: "String field ", number: 1, graduationDate: "10/12/2021", boolean: true, }, ], arr: [ { key1: "value", key2: 1, }, ], address: { Line1: "String field ", city: "1", हिन्दि: "हिन्दि", }, }; const modifiedSourceData = { name: "Test name", age: "20", dob: "10/12/2021", boolean: true, hobbies: ["travelling", "skating", "off-roading"], "%%": "%", हिन्दि: "हिन्दि", primaryEducation: [ { college: "String field ", number: 1, graduationDate: "10/12/2021", boolean: true, }, ], arr: [ { key2: "1", key3: 2, }, ], address: { city: 1, state: "KA", }, }; const expectedRemovedSchemaItems: string[] = [ `${BASE_PATH}.children.education`, `${BASE_PATH}.children.address.children.Line1`, `${BASE_PATH}.children.address.children.xn__j2bd4cyac6f`, `${BASE_PATH}.children.arr.children.${ARRAY_ITEM_KEY}.children.key1`, ]; const expectedModifiedSchemaItems = { [`${BASE_PATH}.children.xn__j2bd4cyac6f`]: schemaItemFactory({ isSpellCheck: false, iconAlign: "left", label: "हिन्दि", sourceData: "हिन्दि", accessor: "हिन्दि", identifier: "xn__j2bd4cyac6f", originalIdentifier: "हिन्दि", defaultValue: '{{((sourceData, formData, fieldState) => (sourceData["हिन्दि"]))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}', position: 8, ...schemaItemStyles, }), [`${BASE_PATH}.children.primaryEducation`]: schemaItemFactory({ backgroundColor: "#FAFAFA", isCollapsible: true, children: { __array_item__: schemaItemFactory({ children: { college: schemaItemFactory({ isSpellCheck: false, defaultValue: undefined, iconAlign: "left", sourceData: "String field ", identifier: "college", position: 0, ...schemaItemStyles, }), number: schemaItemFactory({ isSpellCheck: false, dataType: DataType.NUMBER, defaultValue: undefined, fieldType: FieldType.NUMBER_INPUT, iconAlign: "left", sourceData: 1, identifier: "number", position: 1, ...schemaItemStyles, }), graduationDate: schemaItemFactory({ closeOnSelection: false, dateFormat: "MM/DD/YYYY", label: "Graduation Date", maxDate: "2121-12-31T18:29:00.000Z", minDate: "1920-12-31T18:30:00.000Z", shortcuts: false, defaultValue: undefined, fieldType: FieldType.DATEPICKER, timePrecision: "minute", convertToISO: false, sourceData: "10/12/2021", identifier: "graduationDate", position: 2, ...schemaItemStyles, }), boolean: schemaItemFactory({ alignWidget: "LEFT", dataType: DataType.BOOLEAN, defaultValue: undefined, fieldType: FieldType.SWITCH, sourceData: true, identifier: "boolean", position: 3, backgroundColor: "{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", }), }, dataType: DataType.OBJECT, defaultValue: undefined, fieldType: FieldType.OBJECT, sourceData: { college: "String field ", number: 1, graduationDate: "10/12/2021", boolean: true, }, identifier: ARRAY_ITEM_KEY, position: -1, }), }, dataType: DataType.ARRAY, fieldType: FieldType.ARRAY, sourceData: [ { boolean: true, college: "String field ", graduationDate: "10/12/2021", number: 1, }, ], identifier: "primaryEducation", position: 9, }), [`${BASE_PATH}.children.age`]: schemaItemFactory({ isSpellCheck: false, iconAlign: "left", dataType: DataType.STRING, identifier: "age", position: 1, sourceData: "20", ...schemaItemStyles, }), [`${BASE_PATH}.children.arr.children.${ARRAY_ITEM_KEY}.children.key2`]: schemaItemFactory({ isSpellCheck: false, iconAlign: "left", defaultValue: undefined, sourceData: "1", identifier: "key2", position: 0, ...schemaItemStyles, }), [`${BASE_PATH}.children.arr.children.${ARRAY_ITEM_KEY}.children.key3`]: schemaItemFactory({ isSpellCheck: false, iconAlign: "left", dataType: DataType.NUMBER, defaultValue: undefined, fieldType: FieldType.NUMBER_INPUT, sourceData: 2, identifier: "key3", position: 1, ...schemaItemStyles, }), [`${BASE_PATH}.children.address.children.city`]: schemaItemFactory({ isSpellCheck: false, iconAlign: "left", dataType: DataType.NUMBER, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.address.city))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.NUMBER_INPUT, sourceData: 1, identifier: "city", position: 0, ...schemaItemStyles, }), [`${BASE_PATH}.children.address.children.state`]: schemaItemFactory({ isSpellCheck: false, iconAlign: "left", label: "State", dataType: DataType.STRING, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.address.state))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.TEXT_INPUT, sourceData: "KA", identifier: "state", position: 1, ...schemaItemStyles, }), }; const initialResult = SchemaParser.parse(widgetName, { currSourceData: initialSourceData, schema: {}, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); const updatedResult = SchemaParser.parse(widgetName, { currSourceData: modifiedSourceData, schema: initialResult.schema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(updatedResult.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(updatedResult.removedSchemaItems.sort()).toEqual( expectedRemovedSchemaItems.sort(), ); const schemaWithEvalValues = { [ROOT_SCHEMA_KEY]: replaceBindingWithValue( initialResult.schema[ROOT_SCHEMA_KEY], ), }; const updatedResultWithEval = SchemaParser.parse(widgetName, { currSourceData: modifiedSourceData, schema: schemaWithEvalValues, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(updatedResultWithEval.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(updatedResultWithEval.removedSchemaItems.sort()).toEqual( expectedRemovedSchemaItems.sort(), ); }); it("returns unmodified schema when existing field's value in data source changes to null and back", () => { // Get the initial schema const { schema: initialSchema } = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: {}, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); const expectedRemovedSchemaItems: string[] = []; const expectedModifiedSchemaItems = {}; expect(initialSchema).toEqual(testData.initialDataset.schemaOutput); // Set all keys to null const nulledSourceData = klona(testData.initialDataset.dataSource); set(nulledSourceData, "name", null); set(nulledSourceData, "age", null); set(nulledSourceData, "dob", null); set(nulledSourceData, "boolean", null); set(nulledSourceData, "hobbies", null); set(nulledSourceData, "%%", null); set(nulledSourceData, "हिन्दि", null); set(nulledSourceData, "education", null); set(nulledSourceData, "address", null); // Set the sourceData entry in each SchemaItem to null (only property that changes) const expectedSchema = klona(initialSchema); set(expectedSchema, "__root_schema__.children.name.sourceData", null); set(expectedSchema, "__root_schema__.sourceData.name", null); set(expectedSchema, "__root_schema__.children.age.sourceData", null); set(expectedSchema, "__root_schema__.sourceData.age", null); set(expectedSchema, "__root_schema__.children.dob.sourceData", null); set(expectedSchema, "__root_schema__.sourceData.dob", null); set(expectedSchema, "__root_schema__.children.boolean.sourceData", null); set(expectedSchema, "__root_schema__.sourceData.boolean", null); set(expectedSchema, "__root_schema__.children.hobbies.sourceData", null); set(expectedSchema, "__root_schema__.sourceData.hobbies", null); set(expectedSchema, "__root_schema__.children.education.sourceData", null); set(expectedSchema, "__root_schema__.sourceData.education", null); set(expectedSchema, "__root_schema__.children.__.sourceData", null); set(expectedSchema, "__root_schema__.sourceData['%%']", null); set( expectedSchema, "__root_schema__.children.xn__j2bd4cyac6f.sourceData", null, ); set(expectedSchema, "__root_schema__.sourceData.हिन्दि", null); set(expectedSchema, "__root_schema__.children.address.sourceData", null); set(expectedSchema, "__root_schema__.sourceData.address", null); // Parse with the nulled sourceData const resultWithNullKeys = SchemaParser.parse(widgetName, { currSourceData: nulledSourceData, schema: initialSchema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(resultWithNullKeys.schema).toEqual(expectedSchema); expect(resultWithNullKeys.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(resultWithNullKeys.removedSchemaItems).toEqual( expectedRemovedSchemaItems, ); /** * Parse with initial sourceData to check if previous schema with null sourceData * can still retain the schema structure */ const resultWithRevertedData = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: resultWithNullKeys.schema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(resultWithRevertedData.schema).toEqual( testData.initialDataset.schemaOutput, ); expect(resultWithRevertedData.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(resultWithRevertedData.removedSchemaItems).toEqual( expectedRemovedSchemaItems, ); }); it("returns unmodified schema when existing fields value in data source changes to undefined and back", () => { const expectedRemovedSchemaItems: string[] = []; const expectedModifiedSchemaItems = {}; // Get the initial schema const initialResult = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: {}, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(initialResult.schema).toEqual(testData.initialDataset.schemaOutput); // Set all keys to undefined const undefinedDataSource = klona(testData.initialDataset.dataSource); set(undefinedDataSource, "name", undefined); set(undefinedDataSource, "age", undefined); set(undefinedDataSource, "dob", undefined); set(undefinedDataSource, "boolean", undefined); set(undefinedDataSource, "hobbies", undefined); set(undefinedDataSource, "%%", undefined); set(undefinedDataSource, "हिन्दि", undefined); set(undefinedDataSource, "education", undefined); set(undefinedDataSource, "address", undefined); // Set the sourceData entry in each SchemaItem to undefined (only property that changes) const expectedSchema = klona(initialResult.schema); set(expectedSchema, "__root_schema__.children.name.sourceData", undefined); set(expectedSchema, "__root_schema__.sourceData.name", undefined); set(expectedSchema, "__root_schema__.children.age.sourceData", undefined); set(expectedSchema, "__root_schema__.sourceData.age", undefined); set(expectedSchema, "__root_schema__.children.dob.sourceData", undefined); set(expectedSchema, "__root_schema__.sourceData.dob", undefined); set( expectedSchema, "__root_schema__.children.boolean.sourceData", undefined, ); set(expectedSchema, "__root_schema__.sourceData.boolean", undefined); set( expectedSchema, "__root_schema__.children.hobbies.sourceData", undefined, ); set(expectedSchema, "__root_schema__.sourceData.hobbies", undefined); set( expectedSchema, "__root_schema__.children.education.sourceData", undefined, ); set(expectedSchema, "__root_schema__.sourceData.education", undefined); set(expectedSchema, "__root_schema__.children.__.sourceData", undefined); set(expectedSchema, "__root_schema__.sourceData['%%']", undefined); set( expectedSchema, "__root_schema__.children.xn__j2bd4cyac6f.sourceData", undefined, ); set(expectedSchema, "__root_schema__.sourceData.हिन्दि", undefined); set( expectedSchema, "__root_schema__.children.address.sourceData", undefined, ); set(expectedSchema, "__root_schema__.sourceData.address", undefined); // Parse with the undefined sourceData keys const resultWithUndefinedKeys = SchemaParser.parse(widgetName, { currSourceData: undefinedDataSource, schema: initialResult.schema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(resultWithUndefinedKeys.schema).toEqual(expectedSchema); expect(resultWithUndefinedKeys.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(resultWithUndefinedKeys.removedSchemaItems).toEqual( expectedRemovedSchemaItems, ); /** * Parse with initial sourceData to check if previous schema with null sourceData * can still retain the schema structure */ const resultWithRevertedData = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: resultWithUndefinedKeys.schema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(resultWithRevertedData.schema).toEqual( testData.initialDataset.schemaOutput, ); expect(resultWithRevertedData.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(resultWithRevertedData.removedSchemaItems).toEqual( expectedRemovedSchemaItems, ); }); it("returns unmodified schema when existing inner field's value in data source changes to null and back", () => { const expectedRemovedSchemaItems: string[] = []; const expectedModifiedSchemaItems = {}; // Get the initial schema const initialResult = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: {}, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(initialResult.schema).toEqual(testData.initialDataset.schemaOutput); // Set all keys to null const nulledSourceData = klona(testData.initialDataset.dataSource); set(nulledSourceData, "address.Line1", null); set(nulledSourceData, "address.city", null); set(nulledSourceData, "education[0].college", null); set(nulledSourceData, "education[0].number", null); set(nulledSourceData, "education[0].graduationDate", null); set(nulledSourceData, "education[0].boolean", null); // Set the sourceData entry in each SchemaItem to null (only property that changes) const expectedSchema = klona(initialResult.schema); set( expectedSchema, "__root_schema__.children.address.children.Line1.sourceData", null, ); set(expectedSchema, "__root_schema__.sourceData.address.Line1", null); set( expectedSchema, "__root_schema__.children.address.children.city.sourceData", null, ); set(expectedSchema, "__root_schema__.sourceData.address.city", null); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.children.college.sourceData", null, ); set(expectedSchema, "__root_schema__.children.address.sourceData", { Line1: null, city: null, }); set( expectedSchema, "__root_schema__.sourceData.education[0].college", null, ); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.children.number.sourceData", null, ); set(expectedSchema, "__root_schema__.sourceData.education[0].number", null); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.children.graduationDate.sourceData", null, ); set( expectedSchema, "__root_schema__.sourceData.education[0].graduationDate", null, ); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.children.boolean.sourceData", null, ); set( expectedSchema, "__root_schema__.sourceData.education[0].boolean", null, ); set(expectedSchema, "__root_schema__.children.education.sourceData", [ { college: null, number: null, graduationDate: null, boolean: null, }, ]); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.sourceData", { college: null, number: null, graduationDate: null, boolean: null, }, ); // Parse with the nulled sourceData const resultWithNullKeys = SchemaParser.parse(widgetName, { currSourceData: nulledSourceData, schema: initialResult.schema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(resultWithNullKeys.schema).toEqual(expectedSchema); expect(resultWithNullKeys.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(resultWithNullKeys.removedSchemaItems).toEqual( expectedRemovedSchemaItems, ); /** * Parse with initial sourceData to check if previous schema with null sourceData * can still retain the schema structure */ const schemaWithRevertedData = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: resultWithNullKeys.schema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(schemaWithRevertedData.schema).toEqual( testData.initialDataset.schemaOutput, ); expect(schemaWithRevertedData.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(schemaWithRevertedData.removedSchemaItems).toEqual( expectedRemovedSchemaItems, ); }); it("returns unmodified schema when existing inner field's value in data source changes to undefined and back", () => { const expectedRemovedSchemaItems: string[] = []; const expectedModifiedSchemaItems = {}; // Get the initial schema const initialResult = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: {}, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(initialResult.schema).toEqual(testData.initialDataset.schemaOutput); // Set all keys to undefined const undefinedSourceData = klona(testData.initialDataset.dataSource); set(undefinedSourceData, "address.Line1", undefined); set(undefinedSourceData, "address.city", undefined); set(undefinedSourceData, "education[0].college", undefined); set(undefinedSourceData, "education[0].number", undefined); set(undefinedSourceData, "education[0].graduationDate", undefined); set(undefinedSourceData, "education[0].boolean", undefined); // Set the sourceData entry in each SchemaItem to undefined (only property that changes) const expectedSchema = klona(initialResult.schema); set( expectedSchema, "__root_schema__.children.address.children.Line1.sourceData", undefined, ); set(expectedSchema, "__root_schema__.sourceData.address.Line1", undefined); set( expectedSchema, "__root_schema__.children.address.children.city.sourceData", undefined, ); set(expectedSchema, "__root_schema__.sourceData.address.city", undefined); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.children.college.sourceData", undefined, ); set(expectedSchema, "__root_schema__.children.address.sourceData", { Line1: undefined, city: undefined, }); set( expectedSchema, "__root_schema__.sourceData.education[0].college", undefined, ); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.children.number.sourceData", undefined, ); set( expectedSchema, "__root_schema__.sourceData.education[0].number", undefined, ); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.children.graduationDate.sourceData", undefined, ); set( expectedSchema, "__root_schema__.sourceData.education[0].graduationDate", undefined, ); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.children.boolean.sourceData", undefined, ); set( expectedSchema, "__root_schema__.sourceData.education[0].boolean", undefined, ); set(expectedSchema, "__root_schema__.children.education.sourceData", [ { college: undefined, number: undefined, graduationDate: undefined, boolean: undefined, }, ]); set( expectedSchema, "__root_schema__.children.education.children.__array_item__.sourceData", { college: undefined, number: undefined, graduationDate: undefined, boolean: undefined, }, ); // Parse with the undefined sourceData const resultWithUndefinedKeys = SchemaParser.parse(widgetName, { currSourceData: undefinedSourceData, schema: initialResult.schema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(resultWithUndefinedKeys.schema).toEqual(expectedSchema); expect(resultWithUndefinedKeys.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(resultWithUndefinedKeys.removedSchemaItems).toEqual( expectedRemovedSchemaItems, ); /** * Parse with initial sourceData to check if previous schema with undefined sourceData * can still retain the schema structure */ const resultWithRevertedData = SchemaParser.parse(widgetName, { currSourceData: testData.initialDataset.dataSource, schema: resultWithUndefinedKeys.schema, fieldThemeStylesheets: testData.fieldThemeStylesheets, }); expect(resultWithRevertedData.schema).toEqual( testData.initialDataset.schemaOutput, ); expect(resultWithRevertedData.modifiedSchemaItems).toEqual( expectedModifiedSchemaItems, ); expect(resultWithRevertedData.removedSchemaItems).toEqual( expectedRemovedSchemaItems, ); }); }); describe("#getSchemaItemByFieldType", () => { it("modifies schemaItem based on the fieldType provided", () => { const schema = testData.initialDataset.schemaOutput; const schemaItemPath = "schema.__root_schema__.children.address.children.city"; const schemaItem = get({ schema }, schemaItemPath); const expectedOutput = { isDisabled: false, isRequired: false, label: "City", isVisible: true, children: {}, dataType: DataType.STRING, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.address.city))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.SELECT, sourceData: "1", isCustomField: false, accessor: "city", identifier: "city", originalIdentifier: "city", position: 1, serverSideFiltering: false, isFilterable: false, labelTextSize: "0.875rem", }; const result = SchemaParser.getSchemaItemByFieldType(FieldType.SELECT, { widgetName, schema, schemaItem, schemaItemPath, }); expect(result).toEqual(expectedOutput); }); it("modifies schemaItem with updated name based on the fieldType provided", () => { const schema = testData.initialDataset.schemaOutput; const schemaItemPath = "schema.__root_schema__.children.address.children.city"; const schemaItem = get({ schema }, schemaItemPath); schemaItem.isCustomField = true; schemaItem.accessor = "newCityName"; const expectedOutput = { isDisabled: false, isRequired: false, label: "City", isVisible: true, children: {}, dataType: DataType.STRING, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], defaultValue: "", fieldType: FieldType.SELECT, sourceData: "", isCustomField: true, accessor: "newCityName", identifier: "city", originalIdentifier: "city", position: 1, serverSideFiltering: false, isFilterable: false, labelTextSize: "0.875rem", }; const result = SchemaParser.getSchemaItemByFieldType(FieldType.SELECT, { widgetName, schema, schemaItem, schemaItemPath, }); expect(result).toEqual(expectedOutput); }); it("modifies schemaItem structure when field type is changed from multiselect to flat array", () => { const schema = testData.initialDataset.schemaOutput; const schemaItemPath = "schema.__root_schema__.children.hobbies"; const schemaItem = get({ schema }, schemaItemPath); const expectedOutput = { isDisabled: false, isRequired: false, label: "Hobbies", isVisible: true, backgroundColor: "#FAFAFA", children: { __array_item__: { isDisabled: false, isRequired: false, label: "Array Item", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "travelling", isCustomField: false, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, position: -1, isSpellCheck: false, labelTextSize: "0.875rem", }, }, dataType: DataType.ARRAY, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.hobbies))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.ARRAY, sourceData: ["travelling", "skating", "off-roading"], isCustomField: false, accessor: "hobbies", identifier: "hobbies", originalIdentifier: "hobbies", isCollapsible: true, position: 4, labelTextSize: "0.875rem", }; const result = SchemaParser.getSchemaItemByFieldType(FieldType.ARRAY, { widgetName, schema, schemaItem, schemaItemPath, }); expect(result).toEqual(expectedOutput); }); it("returns modified schemaItem structure when field type is changed from text to array", () => { const schema = testData.initialDataset.schemaOutput; const schemaItemPath = "schema.__root_schema__.children.name"; const schemaItem = get({ schema }, schemaItemPath); const expectedOutput = { isDisabled: false, isRequired: false, label: "Name", isVisible: true, backgroundColor: "#FAFAFA", children: { __array_item__: { isDisabled: false, isRequired: false, label: "Array Item", isVisible: true, children: {}, dataType: DataType.OBJECT, defaultValue: undefined, fieldType: FieldType.OBJECT, sourceData: {}, isCustomField: false, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, position: -1, labelTextSize: "0.875rem", }, }, dataType: DataType.STRING, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.name))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.ARRAY, sourceData: "Test name", isCustomField: false, accessor: "name", identifier: "name", originalIdentifier: "name", isCollapsible: true, position: 0, labelTextSize: "0.875rem", }; const result = SchemaParser.getSchemaItemByFieldType(FieldType.ARRAY, { widgetName, schema, schemaItem, schemaItemPath, }); expect(result).toEqual(expectedOutput); }); }); describe("#getSchemaItemFor", () => { it("returns new schemaItem for a key", () => { const key = "firstName"; const expectedOutput = { isDisabled: false, isRequired: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.firstName))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "firstName", identifier: "firstName", originalIdentifier: "firstName", position: -1, labelTextSize: "0.875rem", isSpellCheck: false, }; const result = SchemaParser.getSchemaItemFor(key, { widgetName, currSourceData: "John", sourceDataPath: "sourceData.firstName", baseSchemaPath: null, removedSchemaItems: [], modifiedSchemaItems: {}, skipDefaultValueProcessing: false, identifier: key, }); expect(result).toEqual(expectedOutput); }); it("returns new schemaItem for a custom field key", () => { const key = "firstName"; const expectedOutput = { isDisabled: false, isRequired: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: true, accessor: "firstName", identifier: "firstName", originalIdentifier: "firstName", position: -1, isSpellCheck: false, labelTextSize: "0.875rem", }; const result = SchemaParser.getSchemaItemFor(key, { widgetName, currSourceData: "John", sourceDataPath: "sourceData.firstName", isCustomField: true, skipDefaultValueProcessing: false, baseSchemaPath: null, removedSchemaItems: [], modifiedSchemaItems: {}, identifier: key, }); expect(result).toEqual(expectedOutput); }); it("returns schemaItem with overridden field type", () => { const key = "firstName"; const expectedOutput = { isDisabled: false, isRequired: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.SWITCH, sourceData: "John", isCustomField: true, accessor: "firstName", identifier: "firstName", originalIdentifier: "firstName", position: -1, alignWidget: "LEFT", labelTextSize: "0.875rem", }; const result = SchemaParser.getSchemaItemFor(key, { widgetName, currSourceData: "John", sourceDataPath: "sourceData.firstName", isCustomField: true, fieldType: FieldType.SWITCH, skipDefaultValueProcessing: false, baseSchemaPath: null, removedSchemaItems: [], modifiedSchemaItems: {}, identifier: key, }); expect(result).toEqual(expectedOutput); }); it("returns array children only if dataType and fieldType are Array", () => { const key = "hobbies"; const expectedOutput = { isDisabled: false, isRequired: false, label: "Hobbies", isVisible: true, children: {}, dataType: DataType.ARRAY, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.hobbies))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.MULTISELECT, sourceData: ["one", "two"], isFilterable: false, isCustomField: false, accessor: "hobbies", identifier: "hobbies", originalIdentifier: "hobbies", position: -1, serverSideFiltering: false, labelTextSize: "0.875rem", options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }; const result = SchemaParser.getSchemaItemFor(key, { widgetName, currSourceData: ["one", "two"], sourceDataPath: "sourceData.hobbies", skipDefaultValueProcessing: false, baseSchemaPath: null, removedSchemaItems: [], modifiedSchemaItems: {}, identifier: key, }); expect(result).toEqual(expectedOutput); }); }); describe("#getUnModifiedSchemaItemFor", () => { it("returns unmodified schemaItem for current data", () => { const schemaItem = { isDisabled: false, isRequired: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.firstName))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "firstName", identifier: "firstName", originalIdentifier: "firstName", position: -1, isSpellCheck: false, }; const currData = "John"; const sourceDataPath = "sourceData.firstName"; const result = SchemaParser.getUnModifiedSchemaItemFor({ currSourceData: currData, schemaItem, sourceDataPath, widgetName, baseSchemaPath: null, removedSchemaItems: [], modifiedSchemaItems: {}, skipDefaultValueProcessing: false, identifier: schemaItem.identifier, }); expect(result).toEqual(schemaItem); }); it("returns array children only if dataType and fieldType are Array", () => { const schemaItem = { isDisabled: false, isRequired: false, label: "Hobbies", isVisible: true, children: {}, dataType: DataType.ARRAY, defaultValue: '{{((sourceData, formData, fieldState) => (sourceData.hobbies.map((item) => ({ "label": item, "value": item }))))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}', fieldType: FieldType.MULTISELECT, sourceData: "John", isCustomField: false, accessor: "hobbies", identifier: "hobbies", originalIdentifier: "hobbies", position: -1, serverSideFiltering: false, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }; const currData = "John"; const sourceDataPath = "sourceData.firstName"; const result = SchemaParser.getUnModifiedSchemaItemFor({ currSourceData: currData, schemaItem, sourceDataPath, widgetName, baseSchemaPath: null, removedSchemaItems: [], modifiedSchemaItems: {}, skipDefaultValueProcessing: false, identifier: schemaItem.identifier, }); expect(result).toEqual(schemaItem); }); }); describe("#convertArrayToSchema", () => { it("returns schema for array data", () => { const removedSchemaItems: string[] = []; const modifiedSchemaItems = {}; const currSourceData = [ { firstName: "John", }, ]; const expectedSchema = { __array_item__: { isDisabled: false, isRequired: false, label: "Array Item", isVisible: true, children: { firstName: { isDisabled: false, isRequired: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "firstName", identifier: "firstName", originalIdentifier: "firstName", position: 0, isSpellCheck: false, labelTextSize: "0.875rem", }, }, dataType: DataType.OBJECT, defaultValue: undefined, fieldType: FieldType.OBJECT, sourceData: { firstName: "John", }, isCustomField: false, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, position: -1, labelTextSize: "0.875rem", }, }; const expectedModifiedSchemaItems = { [`schema.${ROOT_SCHEMA_KEY}.entries.${ARRAY_ITEM_KEY}`]: expectedSchema[ARRAY_ITEM_KEY], }; const result = SchemaParser.convertArrayToSchema({ currSourceData, widgetName, baseSchemaPath: `schema.${ROOT_SCHEMA_KEY}.entries`, removedSchemaItems, modifiedSchemaItems, sourceDataPath: "sourceData.entries", skipDefaultValueProcessing: false, }); expect(result).toEqual(expectedSchema); expect(removedSchemaItems).toEqual([]); expect(modifiedSchemaItems).toEqual(expectedModifiedSchemaItems); }); it("returns modified schema with only modified updates when data changes", () => { const removedSchemaItems: string[] = []; const modifiedSchemaItems = {}; const currSourceData = [ { firstName: "John", lastName: "Doe", }, ]; const prevSchema = { __array_item__: { isDisabled: false, isRequired: false, label: "Array Item", isVisible: false, children: { firstName: { isDisabled: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "Modified default value", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "name", identifier: "firstName", originalIdentifier: "firstName", position: 0, isSpellCheck: true, isRequired: true, }, }, dataType: DataType.OBJECT, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.entries[0]))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.OBJECT, sourceData: { firstName: "John", }, isCustomField: false, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, position: -1, }, }; const expectedSchema = { __array_item__: { isDisabled: false, isRequired: false, label: "Array Item", isVisible: false, children: { firstName: { isDisabled: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "Modified default value", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "name", identifier: "firstName", originalIdentifier: "firstName", position: 0, isSpellCheck: true, isRequired: true, }, lastName: { isDisabled: false, isRequired: false, label: "Last Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "Doe", isCustomField: false, accessor: "lastName", identifier: "lastName", originalIdentifier: "lastName", position: 1, isSpellCheck: false, labelTextSize: "0.875rem", }, }, dataType: DataType.OBJECT, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.entries[0]))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.OBJECT, sourceData: { firstName: "John", lastName: "Doe", }, isCustomField: false, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, position: -1, }, }; const expectedModifiedSchemaItems = { [`schema.${ROOT_SCHEMA_KEY}.entries.${ARRAY_ITEM_KEY}.children.lastName`]: expectedSchema[ARRAY_ITEM_KEY].children.lastName, }; const result = SchemaParser.convertArrayToSchema({ currSourceData, widgetName, sourceDataPath: "sourceData.entries", baseSchemaPath: `schema.${ROOT_SCHEMA_KEY}.entries`, removedSchemaItems, modifiedSchemaItems, prevSchema, skipDefaultValueProcessing: false, }); expect(result).toEqual(expectedSchema); expect(result).toEqual(expectedSchema); expect(removedSchemaItems).toEqual([]); expect(modifiedSchemaItems).toEqual(expectedModifiedSchemaItems); }); }); describe("#convertObjectToSchema", () => { it("returns schema for object data", () => { const currSourceData = { firstName: "John", }; const expectedSchema = { firstName: { isDisabled: false, isRequired: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.entry.firstName))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "firstName", identifier: "firstName", originalIdentifier: "firstName", position: 0, isSpellCheck: false, labelTextSize: "0.875rem", }, }; const result = SchemaParser.convertObjectToSchema({ baseSchemaPath: null, currSourceData, modifiedSchemaItems: {}, removedSchemaItems: [], skipDefaultValueProcessing: false, sourceDataPath: "sourceData.entry", widgetName, }); expect(result).toEqual(expectedSchema); }); it("returns modified schema with only modified updates when data changes", () => { const currSourceData = { firstName: "John", lastName: "Doe", }; const prevSchema = { firstName: { isDisabled: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "Modified default value", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "name", identifier: "firstName", originalIdentifier: "firstName", position: 0, isSpellCheck: true, isRequired: true, }, }; const expectedSchema = { firstName: { isDisabled: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "Modified default value", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "name", identifier: "firstName", originalIdentifier: "firstName", position: 0, isSpellCheck: true, isRequired: true, }, lastName: { isDisabled: false, isRequired: false, label: "Last Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.entries.lastName))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "Doe", labelTextSize: "0.875rem", isCustomField: false, accessor: "lastName", identifier: "lastName", originalIdentifier: "lastName", position: 1, isSpellCheck: false, }, }; const result = SchemaParser.convertObjectToSchema({ currSourceData, widgetName, sourceDataPath: "sourceData.entries", prevSchema, baseSchemaPath: null, removedSchemaItems: [], modifiedSchemaItems: {}, skipDefaultValueProcessing: false, }); expect(result).toEqual(expectedSchema); }); it("returns modified schema with only modified updates when similar keys are passed", () => { const currSourceData = { firstName: "John", "##": "Doe", "%%": "Some other value", }; const prevSchema = { firstName: { isDisabled: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "Modified default value", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "name", identifier: "firstName", originalIdentifier: "firstName", position: 0, isSpellCheck: true, isRequired: true, }, __: { isDisabled: false, isRequired: false, label: "##", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: '{{((sourceData, formData, fieldState) => (sourceData.entries["##"]))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}', fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "Doe", isCustomField: false, accessor: "##", identifier: "__", originalIdentifier: "##", position: 1, isSpellCheck: false, }, }; const expectedSchema = { firstName: { isDisabled: false, label: "First Name", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: "Modified default value", fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "John", isCustomField: false, accessor: "name", identifier: "firstName", originalIdentifier: "firstName", position: 0, isSpellCheck: true, isRequired: true, }, __: { isDisabled: false, isRequired: false, label: "##", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: '{{((sourceData, formData, fieldState) => (sourceData.entries["##"]))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}', fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "Doe", isCustomField: false, accessor: "##", identifier: "__", originalIdentifier: "##", position: 1, isSpellCheck: false, }, __1: { isDisabled: false, isRequired: false, label: "%%", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: '{{((sourceData, formData, fieldState) => (sourceData.entries["%%"]))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}', fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "Some other value", labelTextSize: "0.875rem", isCustomField: false, accessor: "%%", identifier: "__1", originalIdentifier: "%%", position: 2, isSpellCheck: false, }, }; const result = SchemaParser.convertObjectToSchema({ currSourceData, widgetName, sourceDataPath: "sourceData.entries", baseSchemaPath: null, removedSchemaItems: [], modifiedSchemaItems: {}, prevSchema, skipDefaultValueProcessing: false, }); expect(result).toEqual(expectedSchema); }); }); describe(".constructPlausibleObjectFromArray", () => { it("returns an object from array of objects", () => { const input = [ { firstName: "20" }, { lastName: 30 }, { foo: { bar: 20, zoo: "test" } }, { lastName: 20, addresses: [{ line1: "line1" }] }, { foo: { bar: { zoo: 100 } } }, ]; const expectedOutput = { firstName: "20", lastName: 20, addresses: [{ line1: "line1" }], foo: { zoo: "test", bar: { zoo: 100 } }, }; const result = constructPlausibleObjectFromArray(input); expect(result).toEqual(expectedOutput); }); }); describe(".getSourcePath", () => { it("returns path with object notation when name is string", () => { const input = "test"; const basePath = "sourceData.obj"; const resultWithBasePath = getSourcePath(input, basePath); const resultWithoutBasePath = getSourcePath(input); expect(resultWithBasePath).toEqual("sourceData.obj.test"); expect(resultWithoutBasePath).toEqual(".test"); }); it("returns path with bracket notation when name is number", () => { const input = 0; const basePath = "sourceData.arr"; const resultWithBasePath = getSourcePath(input, basePath); const resultWithoutBasePath = getSourcePath(input); expect(resultWithBasePath).toEqual("sourceData.arr[0]"); expect(resultWithoutBasePath).toEqual("[0]"); }); it("returns path with bracket notation when name cannot be used in dot notation", () => { const input = "first name"; const basePath = "sourceData.arr"; const resultWithBasePath = getSourcePath(input, basePath); const resultWithoutBasePath = getSourcePath(input); expect(resultWithBasePath).toEqual('sourceData.arr["first name"]'); expect(resultWithoutBasePath).toEqual('["first name"]'); }); }); describe(".getSourceDataPathFromSchemaItemPath", () => { it("returns source data path from schema item path", () => { const inputs = [ "schema.__root_schema__.children.name", "schema.__root_schema__.children.education.children.__array_item__.children.college", "schema.__root_schema__.children.address.children.Line1", "schema.__root_schema__.children.education.children.__array_item__", "schema.__root_schema__.children.education", "schema.__root_schema__.children.__", ]; const expectedOutputs = [ "sourceData.name", "sourceData.education[0].college", "sourceData.address.Line1", "sourceData.education[0]", "sourceData.education", 'sourceData["%%"]', ]; inputs.forEach((input, index) => { const result = getSourceDataPathFromSchemaItemPath( testData.initialDataset.schemaOutput, input, ); expect(result).toEqual(expectedOutputs[index]); }); }); }); describe(".dataTypeFor", () => { it("returns data type or the passed data", () => { const inputs = [ "string", 10, [], null, undefined, {}, () => { 10; }, ]; const expectedOutputs = [ DataType.STRING, DataType.NUMBER, DataType.ARRAY, DataType.NULL, DataType.UNDEFINED, DataType.OBJECT, DataType.FUNCTION, ]; inputs.forEach((input, index) => { const result = dataTypeFor(input); expect(result).toEqual(expectedOutputs[index]); }); }); }); describe(".subDataTypeFor", () => { it("return sub data type of data passed", () => { const inputs = [ "string", 10, [{}], [""], [1], [null], null, undefined, { foo: "" }, () => { 10; }, ]; const expectedOutputs = [ undefined, undefined, DataType.OBJECT, DataType.STRING, DataType.NUMBER, DataType.NULL, undefined, undefined, undefined, undefined, ]; inputs.forEach((input, index) => { const result = subDataTypeFor(input); expect(result).toEqual(expectedOutputs[index]); }); }); }); describe(".normalizeArrayValue", () => { it("returns returns normalized sub value of an array", () => { const inputs = [[""], [1, 2], [{ firstName: 10 }], [], [null]]; const expectedOutputs = ["", 1, { firstName: 10 }, undefined, null]; inputs.forEach((input, index) => { const result = normalizeArrayValue(input); expect(result).toEqual(expectedOutputs[index]); }); }); }); describe(".fieldTypeFor", () => { it("return default field type of data passed", () => { const inputAndExpectedOutputs: [any, FieldType][] = [ ["string", FieldType.TEXT_INPUT], ["2021-12-30T10:36:12.1212+05:30", FieldType.DATEPICKER], ["December 30, 2021 10:36 AM", FieldType.DATEPICKER], ["December 30, 2021", FieldType.DATEPICKER], ["2021-12-30 10:36", FieldType.DATEPICKER], ["2021-12-30T10:36:12", FieldType.DATEPICKER], ["2021-12-30 10:36:12 AM", FieldType.DATEPICKER], ["30/12/2021 10:36", FieldType.DATEPICKER], ["30 December, 2021", FieldType.DATEPICKER], ["10:36 AM 30 December, 2021", FieldType.DATEPICKER], ["2021-12-30", FieldType.DATEPICKER], ["12-30-2021", FieldType.DATEPICKER], ["30-12-2021", FieldType.DATEPICKER], ["12/30/2021", FieldType.DATEPICKER], ["30/12/2021", FieldType.DATEPICKER], ["30/12/21", FieldType.DATEPICKER], ["12/30/21", FieldType.DATEPICKER], ["40/10/40", FieldType.TEXT_INPUT], ["2000/10", FieldType.TEXT_INPUT], ["1", FieldType.TEXT_INPUT], ["#111", FieldType.TEXT_INPUT], ["999", FieldType.TEXT_INPUT], ["[email protected]", FieldType.EMAIL_INPUT], ["[email protected]", FieldType.TEXT_INPUT], [10, FieldType.NUMBER_INPUT], [[{}], FieldType.ARRAY], [[""], FieldType.MULTISELECT], [[1], FieldType.MULTISELECT], [[null], FieldType.MULTISELECT], [null, FieldType.TEXT_INPUT], [undefined, FieldType.TEXT_INPUT], [{ foo: "" }, FieldType.OBJECT], [ () => { 10; }, FieldType.TEXT_INPUT, ], ]; inputAndExpectedOutputs.forEach(([input, expectedOutput]) => { const result = fieldTypeFor(input); expect(result).toEqual(expectedOutput); }); }); }); describe(".getKeysFromSchema", () => { it("return all the first level keys in a schema which are not custom", () => { const expectedOutput = [ "name", "age", "dob", "boolean", "hobbies", "%%", "हिन्दि", "education", "address", ]; const result = getKeysFromSchema( testData.initialDataset.schemaOutput.__root_schema__.children, ["originalIdentifier"], ); expect(result).toEqual(expectedOutput); }); it("return empty array for empty schema", () => { const result = getKeysFromSchema({}, ["originalIdentifier"]); expect(result).toEqual([]); }); it("return keys for non custom fields only", () => { const schema = klona( testData.initialDataset.schemaOutput.__root_schema__.children, ); schema.name.isCustomField = true; const expectedOutput = [ "age", "dob", "boolean", "hobbies", "%%", "हिन्दि", "education", "address", ]; const result = getKeysFromSchema(schema, ["originalIdentifier"], { onlyNonCustomFieldKeys: true, }); expect(result).toEqual(expectedOutput); }); it("return keys and including custom field keys", () => { const schema = klona( testData.initialDataset.schemaOutput.__root_schema__.children, ); schema.name.isCustomField = true; const expectedOutput = [ "name", "age", "dob", "boolean", "hobbies", "%%", "हिन्दि", "education", "address", ]; const result = getKeysFromSchema(schema, ["originalIdentifier"]); expect(result).toEqual(expectedOutput); }); it("return only custom field keys", () => { const schema = klona( testData.initialDataset.schemaOutput.__root_schema__.children, ); schema.name.isCustomField = true; const expectedOutput = ["name"]; const result = getKeysFromSchema(schema, ["originalIdentifier"], { onlyCustomFieldKeys: true, }); expect(result).toEqual(expectedOutput); }); }); describe("#applyPositions", () => { it("applies positions to new keys added to the schema ", () => { const schema: Schema = klona( testData.initialDataset.schemaOutput.__root_schema__.children, ); schema["firstNewField"] = { position: -1, } as SchemaItem; schema["secondNewField"] = { position: -1, } as SchemaItem; const newKeys = ["firstNewField", "secondNewField"]; applyPositions(schema, newKeys); expect(schema.name.position).toEqual(0); expect(schema.age.position).toEqual(1); expect(schema.dob.position).toEqual(2); expect(schema.boolean.position).toEqual(3); expect(schema.hobbies.position).toEqual(4); expect(schema.__.position).toEqual(5); expect(schema.xn__j2bd4cyac6f.position).toEqual(6); expect(schema.education.position).toEqual(7); expect(schema.address.position).toEqual(8); expect(schema.firstNewField.position).toEqual(9); expect(schema.secondNewField.position).toEqual(10); }); it("repositions any when keys are deleted only when new keys added to the schema ", () => { const schema: Schema = klona( testData.initialDataset.schemaOutput.__root_schema__.children, ); schema["firstNewField"] = { position: -1, } as SchemaItem; schema["secondNewField"] = { position: -1, } as SchemaItem; delete schema.education; delete schema.dob; const newKeys = ["firstNewField", "secondNewField"]; applyPositions(schema, newKeys); expect(schema.name.position).toEqual(0); expect(schema.age.position).toEqual(1); expect(schema.boolean.position).toEqual(2); expect(schema.hobbies.position).toEqual(3); expect(schema.__.position).toEqual(4); expect(schema.xn__j2bd4cyac6f.position).toEqual(5); expect(schema.address.position).toEqual(6); expect(schema.firstNewField.position).toEqual(7); expect(schema.secondNewField.position).toEqual(8); expect(schema.dob).toBeUndefined(); expect(schema.education).toBeUndefined(); }); }); describe(".checkIfArrayAndSubDataTypeChanged", () => { it("return true if passed data is array and it's sub value type changed", () => { const currData = [{}]; const prevData = [""]; const result = checkIfArrayAndSubDataTypeChanged(currData, prevData); expect(result).toEqual(true); }); it("return true if passed data is array and it's sub value type changed", () => { const currData = [{}]; const prevData = [{}]; const result = checkIfArrayAndSubDataTypeChanged(currData, prevData); expect(result).toEqual(false); }); }); describe(".hasNullOrUndefined", () => { it("returns false when one of the parameter is null or undefined", () => { const inputAndExpectedOutputs: [[any, any], boolean][] = [ [["1", "2"], false], [[0, ""], false], [[undefined, "2"], true], [[undefined, null], true], [[undefined, undefined], true], [[null, null], true], [[null, "null"], true], [["null", "null"], false], [["undefined", "undefined"], false], [[0, 0], false], [["", ""], false], ]; inputAndExpectedOutputs.forEach(([input, expectedOutput]) => { const result = hasNullOrUndefined(input); expect(result).toEqual(expectedOutput); }); }); });
1,757
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/fields/ArrayField.test.tsx
import React from "react"; import "@testing-library/jest-dom"; import { render } from "@testing-library/react"; import { FormProvider, useForm } from "react-hook-form"; import ArrayField from "./ArrayField"; import { FormContextProvider } from "../FormContext"; import { ThemeProvider } from "styled-components"; const schemaItem = { children: { __array_item__: { children: { name: { children: {}, dataType: "string", fieldType: "Text Input", sourceData: "Crime", isCustomField: false, accessor: "name", identifier: "name", position: 0, originalIdentifier: "name", accentColor: "#553DE9", borderRadius: "0.375rem", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Name", iconName: "", labelStyle: "", labelTextColor: "", placeholderText: "", tooltip: "", errorMessage: "", validation: true, regex: "", }, id: { children: {}, dataType: "number", fieldType: "Number Input", sourceData: 80, isCustomField: false, accessor: "id", identifier: "id", position: 1, originalIdentifier: "id", accentColor: "#553DE9", borderRadius: "0.375rem", boxShadow: "none", iconAlign: "left", isDisabled: false, isRequired: false, isSpellCheck: false, isVisible: true, labelTextSize: "0.875rem", label: "Id", iconName: "", labelStyle: "", labelTextColor: "", placeholderText: "", tooltip: "", errorMessage: "", validation: true, regex: "", }, }, dataType: "object", fieldType: "Object", sourceData: { name: "Crime", id: 80, }, isCustomField: false, accessor: "__array_item__", identifier: "__array_item__", position: -1, originalIdentifier: "__array_item__", borderRadius: "0.375rem", boxShadow: "none", cellBorderRadius: "0.375rem", cellBoxShadow: "none", isDisabled: false, isRequired: false, isVisible: true, labelTextSize: "0.875rem", label: "Array Item", borderColor: "", backgroundColor: "", labelStyle: "", labelTextColor: "", }, }, dataType: "array", defaultValue: '[\n {\n "name": "Comedy",\n "id": 35\n },\n {\n "name": "Crime",\n "id": 80\n }\n]', fieldType: "Array", sourceData: [ { name: "Comedy", id: 35, }, { name: "Crime", id: 80, }, ], isCustomField: false, accessor: "genres", identifier: "genres", position: 3, originalIdentifier: "genres", accentColor: "#553DE9", borderRadius: "0.375rem", boxShadow: "none", isDisabled: false, isRequired: false, isVisible: true, labelTextSize: "0.875rem", label: "Genres", cellBorderColor: "", cellBackgroundColor: "", borderColor: "", labelStyle: "", labelTextColor: "", tooltip: "", cellBorderRadius: "0.375rem", cellBoxShadow: "none", backgroundColor: "#FAFAFA", isCollapsible: true, }; describe("ArrayField", () => { it("check if stringified defaultValue array generates correct number of array fields", async () => { const mocksetMetaInternalFieldState = jest.fn(); const TestComponent = () => { const methods = useForm({ defaultValues: { genres: schemaItem.defaultValue, }, }); return ( <ThemeProvider theme={ { colors: { icon: { normal: "#C5C5C5", hover: "#4B4848", active: "#302D2D", }, }, } as any } > <FormContextProvider executeAction={jest.fn} renderMode="CANVAS" setMetaInternalFieldState={mocksetMetaInternalFieldState} updateFormData={jest.fn} updateWidgetMetaProperty={jest.fn} updateWidgetProperty={jest.fn} > <FormProvider {...methods}> <ArrayField fieldClassName={"genres"} name={"genres"} passedDefaultValue={[ { name: "Comedy", id: 35, }, { name: "Crime", id: 80, }, ]} propertyPath={"schema.__root_schema__.children.genres"} schemaItem={schemaItem} /> </FormProvider> </FormContextProvider> </ThemeProvider> ); }; const { container } = render(<TestComponent />); expect( container.getElementsByClassName("t--jsonformfield-genres-item").length, ).toBe(2); }); it("check if defaultValue array generates correct number of array fields", async () => { const mocksetMetaInternalFieldState = jest.fn(); const TestComponent = () => { schemaItem.defaultValue = [ { name: "Comedy", id: 35, }, { name: "Crime", id: 80, }, ] as any; const methods = useForm({ defaultValues: { genres: schemaItem.defaultValue, }, }); return ( <ThemeProvider theme={ { colors: { icon: { normal: "#C5C5C5", hover: "#4B4848", active: "#302D2D", }, }, } as any } > <FormContextProvider executeAction={jest.fn} renderMode="CANVAS" setMetaInternalFieldState={mocksetMetaInternalFieldState} updateFormData={jest.fn} updateWidgetMetaProperty={jest.fn} updateWidgetProperty={jest.fn} > <FormProvider {...methods}> <ArrayField fieldClassName={"genres"} name={"genres"} passedDefaultValue={[ { name: "Comedy", id: 35, }, { name: "Crime", id: 80, }, ]} propertyPath={"schema.__root_schema__.children.genres"} schemaItem={schemaItem} /> </FormProvider> </FormContextProvider> </ThemeProvider> ); }; const { container } = render(<TestComponent />); expect( container.getElementsByClassName("t--jsonformfield-genres-item").length, ).toBe(2); }); });
1,761
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/fields/CurrencyInputField.test.ts
import type { CurrencyInputFieldProps } from "./CurrencyInputField"; import { isValid } from "./CurrencyInputField"; describe("Currency Input Field", () => { it("return validity when not required", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { isRequired: false, } as CurrencyInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when required", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { isRequired: true, } as CurrencyInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is true", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: true, } as CurrencyInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: false, } as CurrencyInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false with required true", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { validation: false, isRequired: true, } as CurrencyInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); });
1,765
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/fields/InputField.test.ts
import { FieldType } from "../constants"; import type { InputFieldProps } from "./InputField"; import { isValid } from "./InputField"; describe("Input Field - Number", () => { it("return validity when not required", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { isRequired: false, fieldType: FieldType.NUMBER_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when required", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { isRequired: true, fieldType: FieldType.NUMBER_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is true", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: true, fieldType: FieldType.NUMBER_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: false, fieldType: FieldType.NUMBER_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false with required true", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { validation: false, isRequired: true, fieldType: FieldType.NUMBER_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); }); describe("Input Field - Text/Password/Multiline", () => { it("return validity when not required", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: true }, { value: "1.2.1", expectedOutput: true }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { isRequired: false, fieldType: FieldType.TEXT_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when required", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: true }, { value: "1.2.1", expectedOutput: true }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { isRequired: true, fieldType: FieldType.TEXT_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is true", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: true }, { value: "1.2.1", expectedOutput: true }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: true, fieldType: FieldType.TEXT_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: false, fieldType: FieldType.TEXT_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false with required true", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { validation: false, isRequired: true, fieldType: FieldType.TEXT_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); }); describe("Input Field - Email", () => { it("return validity when not required", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: "[email protected]", expectedOutput: true }, { value: "[email protected]", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { isRequired: false, fieldType: FieldType.EMAIL_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when required", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: "[email protected]", expectedOutput: true }, { value: "[email protected]", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { isRequired: true, fieldType: FieldType.EMAIL_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is true", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: "[email protected]", expectedOutput: true }, { value: "[email protected]", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: true, fieldType: FieldType.EMAIL_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: "[email protected]", expectedOutput: false }, { value: "[email protected]", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: false, fieldType: FieldType.EMAIL_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false with required true", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: "[email protected]", expectedOutput: false }, { value: "[email protected]", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { validation: false, isRequired: true, fieldType: FieldType.EMAIL_INPUT, } as InputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); });
1,769
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/fields/PhoneInputField.test.ts
import { FieldType } from "../constants"; import type { PhoneInputFieldProps } from "./PhoneInputField"; import { isValid } from "./PhoneInputField"; describe("Phone Input Field", () => { it("return validity when not required", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: true }, { value: "1.2.1", expectedOutput: true }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { isRequired: false, fieldType: FieldType.TEXT_INPUT, } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when required", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: true }, { value: "1.2.1", expectedOutput: true }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { isRequired: true, fieldType: FieldType.TEXT_INPUT, } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is true", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: true }, { value: "1.2.1", expectedOutput: true }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: true, fieldType: FieldType.TEXT_INPUT, } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { validation: false, fieldType: FieldType.TEXT_INPUT, } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("return validity when validation is false with required true", () => { const inputs = [ { value: "", expectedOutput: false }, { value: "0", expectedOutput: false }, { value: "1", expectedOutput: false }, { value: "-1", expectedOutput: false }, { value: "1.2", expectedOutput: false }, { value: "1.200", expectedOutput: false }, { value: "asd", expectedOutput: false }, { value: "1.2.1", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { validation: false, isRequired: true, fieldType: FieldType.TEXT_INPUT, } as PhoneInputFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); });
1,772
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/fields/SelectField.test.tsx
import type { SelectFieldProps } from "./SelectField"; import { isValid } from "./SelectField"; describe(".isValid", () => { it("returns true when isRequired is false", () => { const inputs = [ { value: "", expectedOutput: true }, { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: true }, { value: "1.2.1", expectedOutput: true }, { value: 0, expectedOutput: true }, { value: 1, expectedOutput: true }, { value: -1, expectedOutput: true }, { value: null, expectedOutput: true }, { value: undefined, expectedOutput: true }, ]; const schemaItem = { isRequired: false, } as SelectFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("returns true when isRequired is true and value is valid", () => { const inputs = [ { value: "0", expectedOutput: true }, { value: "1", expectedOutput: true }, { value: "-1", expectedOutput: true }, { value: "1.2", expectedOutput: true }, { value: "1.200", expectedOutput: true }, { value: "asd", expectedOutput: true }, { value: "1.2.1", expectedOutput: true }, { value: 0, expectedOutput: true }, { value: 1, expectedOutput: true }, { value: -1, expectedOutput: true }, ]; const schemaItem = { isRequired: true, } as SelectFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); it("returns false when isRequired is true and value is invalid", () => { const inputs = [ { value: "", expectedOutput: false }, { value: null, expectedOutput: false }, { value: undefined, expectedOutput: false }, ]; const schemaItem = { isRequired: true, } as SelectFieldProps["schemaItem"]; inputs.forEach((input) => { const result = isValid(schemaItem, input.value); expect(result).toEqual(input.expectedOutput); }); }); });
1,778
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/fields/useRegisterFieldValidity.test.tsx
import React from "react"; import { renderHook } from "@testing-library/react-hooks"; import { FormProvider, useForm } from "react-hook-form"; import { FormContextProvider } from "../FormContext"; import type { UseRegisterFieldValidityProps } from "./useRegisterFieldValidity"; import useRegisterFieldValidity from "./useRegisterFieldValidity"; import { FieldType } from "../constants"; const initialFieldState = { metaInternalFieldState: { lastName: { isValid: false, }, firstName: { isValid: false, }, array: [ { first: { isValid: false, }, }, ], }, }; describe("useRegisterFieldInvalid", () => { it("updates fieldState and error state with the updated isValid value", () => { const mocksetMetaInternalFieldState = jest.fn(); function Wrapper({ children }: any) { const methods = useForm(); return ( <FormContextProvider executeAction={jest.fn} renderMode="CANVAS" setMetaInternalFieldState={mocksetMetaInternalFieldState} updateFormData={jest.fn} updateWidgetMetaProperty={jest.fn} updateWidgetProperty={jest.fn} > <FormProvider {...methods}>{children}</FormProvider> </FormContextProvider> ); } const fieldName = "array[0].first"; const { rerender } = renderHook( ({ fieldName, isValid }: UseRegisterFieldValidityProps) => useRegisterFieldValidity({ isValid, fieldName, fieldType: FieldType.TEXT_INPUT, }), { wrapper: Wrapper, initialProps: { isValid: false, fieldName, fieldType: FieldType.TEXT_INPUT, }, }, ); const expectedUpdatedFieldState = { metaInternalFieldState: { lastName: { isValid: false, }, firstName: { isValid: false, }, array: [ { first: { isValid: true, }, }, ], }, }; expect(mocksetMetaInternalFieldState).toBeCalledTimes(1); rerender({ isValid: true, fieldName, fieldType: FieldType.TEXT_INPUT, }); expect(mocksetMetaInternalFieldState).toBeCalledTimes(2); const cbResult = mocksetMetaInternalFieldState.mock.calls[1][0](initialFieldState); expect(cbResult).toEqual(expectedUpdatedFieldState); }); it("does not trigger meta update if field validity is same", () => { const mocksetMetaInternalFieldState = jest.fn(); function Wrapper({ children }: any) { const methods = useForm(); return ( <FormContextProvider executeAction={jest.fn} renderMode="CANVAS" setMetaInternalFieldState={mocksetMetaInternalFieldState} updateFormData={jest.fn} updateWidgetMetaProperty={jest.fn} updateWidgetProperty={jest.fn} > <FormProvider {...methods}>{children}</FormProvider> </FormContextProvider> ); } const fieldName = "array[0].first"; const { rerender } = renderHook( () => useRegisterFieldValidity({ isValid: false, fieldName, fieldType: FieldType.TEXT_INPUT, }), { wrapper: Wrapper, }, ); rerender({ isValid: true, fieldName, fieldType: FieldType.TEXT_INPUT, }); expect(mocksetMetaInternalFieldState).toBeCalledTimes(1); rerender({ isValid: true, fieldName, fieldType: FieldType.TEXT_INPUT, }); expect(mocksetMetaInternalFieldState).toBeCalledTimes(1); }); });
1,781
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/helper.test.ts
import type { FieldThemeStylesheet, Schema } from "../constants"; import { ARRAY_ITEM_KEY, DataType, FieldType, ROOT_SCHEMA_KEY, } from "../constants"; import schemaTestData from "../schemaTestData"; import { ComputedSchemaStatus, computeSchema, dynamicPropertyPathListFromSchema, generateFieldState, getGrandParentPropertyPath, getParentPropertyPath, } from "./helper"; describe(".getParentPropertyPath", () => { it("returns parent path", () => { const inputs = ["", "a.b.c", "a", "a.b"]; const expectedOutputs = ["", "a.b", "", "a"]; inputs.forEach((input, index) => { const result = getParentPropertyPath(input); expect(result).toEqual(expectedOutputs[index]); }); }); }); describe(".getGrandParentPropertyPath", () => { it("returns parent path", () => { const inputs = ["", "a.b.c", "a", "a.b", "a.b.c.d"]; const expectedOutputs = ["", "a", "", "", "a.b"]; inputs.forEach((input, index) => { const result = getGrandParentPropertyPath(input); expect(result).toEqual(expectedOutputs[index]); }); }); }); describe(".generateFieldState", () => { it("returns fieldState for initial render", () => { const { schemaOutput } = schemaTestData.initialDataset; const metaInternalFieldState = {}; const expectedOutput = { name: { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, age: { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, dob: { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, boolean: { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, hobbies: { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, "%%": { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, हिन्दि: { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, education: [], address: { Line1: { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, city: { isRequired: false, isDisabled: false, isVisible: true, isValid: undefined, }, }, }; const result = generateFieldState(schemaOutput, metaInternalFieldState); expect(result).toEqual(expectedOutput); }); it("returns updated fieldState same prevFieldState and empty metaInternalFieldState", () => { const schema = { __root_schema__: { children: { customField1: { children: {}, dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, sourceData: "", isCustomField: true, name: "customField1", accessor: "customField1", identifier: "customField1", position: 0, originalIdentifier: "customField1", isDisabled: false, label: "Custom Field 1", isVisible: true, isRequired: true, isSpellCheck: false, }, array: { children: { __array_item__: { children: { name: { children: {}, dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, sourceData: "", isCustomField: false, accessor: "name", identifier: "name", position: 0, originalIdentifier: "name", isDisabled: false, label: "Name", isVisible: true, isSpellCheck: false, }, }, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, sourceData: { name: "", }, isCustomField: false, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, position: -1, originalIdentifier: ARRAY_ITEM_KEY, isDisabled: false, label: "Array Item", isVisible: true, }, }, dataType: DataType.ARRAY, defaultValue: "", fieldType: FieldType.ARRAY, sourceData: [ { name: "", }, ], isCustomField: false, accessor: "array", identifier: "array", position: 1, originalIdentifier: "array", isCollapsible: true, isDisabled: false, isVisible: true, label: "Array", }, }, dataType: DataType.OBJECT, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.OBJECT, sourceData: { array: [ { name: "", }, ], }, isCustomField: false, accessor: "", identifier: "", position: -1, originalIdentifier: "", isDisabled: false, isRequired: false, isVisible: true, label: "", }, }; const metaInternalFieldState = {}; const expectedOutput = { customField1: { isRequired: true, isDisabled: false, isVisible: true, isValid: undefined, }, array: [], }; const result = generateFieldState(schema, metaInternalFieldState); expect(result).toEqual(expectedOutput); }); it("returns updated fieldState same prevFieldState and partial metaInternalFieldState", () => { const schema = { __root_schema__: { children: { customField1: { children: {}, dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, sourceData: "", isCustomField: true, accessor: "customField1", identifier: "customField1", position: 0, originalIdentifier: "customField1", isDisabled: false, label: "Custom Field 1", isVisible: true, isRequired: true, isSpellCheck: false, }, array: { children: { __array_item__: { children: { name: { children: {}, dataType: DataType.STRING, fieldType: FieldType.TEXT_INPUT, sourceData: "", isCustomField: false, accessor: "name", identifier: "name", position: 0, originalIdentifier: "name", isDisabled: false, label: "Name", isVisible: true, isSpellCheck: false, isRequired: false, }, }, dataType: DataType.OBJECT, fieldType: FieldType.OBJECT, sourceData: { name: "", }, isCustomField: false, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, position: -1, originalIdentifier: ARRAY_ITEM_KEY, isDisabled: false, label: "Array Item", isVisible: true, }, }, dataType: DataType.ARRAY, defaultValue: "", fieldType: FieldType.ARRAY, sourceData: [ { name: "", }, ], isCustomField: false, accessor: "array", identifier: "array", position: 1, originalIdentifier: "array", isCollapsible: true, isDisabled: false, isVisible: true, label: "Array", }, }, dataType: DataType.OBJECT, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.OBJECT, sourceData: { array: [ { name: "", }, ], }, isCustomField: false, accessor: "", identifier: "", position: -1, originalIdentifier: "", isDisabled: false, isRequired: false, isVisible: true, label: "", }, }; const inputAndExpectedOutput = [ { metaInternalFieldState: { customField1: { isValid: true }, array: [], }, expectedOutput: { customField1: { isRequired: true, isDisabled: false, isVisible: true, isValid: true, }, array: [], }, }, { metaInternalFieldState: { customField1: { isValid: false }, array: [{ name: { isValid: false } }, { name: { isValid: true } }], }, expectedOutput: { customField1: { isRequired: true, isDisabled: false, isVisible: true, isValid: false, }, array: [ { name: { isRequired: false, isDisabled: false, isVisible: true, isValid: false, }, }, { name: { isRequired: false, isDisabled: false, isVisible: true, isValid: true, }, }, ], }, }, ]; inputAndExpectedOutput.forEach( ({ expectedOutput, metaInternalFieldState }) => { const result = generateFieldState(schema, metaInternalFieldState); expect(result).toEqual(expectedOutput); }, ); }); }); describe(".dynamicPropertyPathListFromSchema", () => { it("returns valid auto JS enabled propertyPaths", () => { const schema = { [ROOT_SCHEMA_KEY]: { identifier: ROOT_SCHEMA_KEY, fieldType: FieldType.OBJECT, children: { name: { fieldType: FieldType.TEXT_INPUT, identifier: "name", defaultValue: "{{sourceData.name}}", }, dob: { fieldType: FieldType.DATEPICKER, identifier: "dob", defaultValue: "{{sourceData.{dob}}", }, obj: { fieldType: FieldType.OBJECT, identifier: "obj", defaultValue: "{{sourceData.{obj}}", children: { agree: { fieldType: FieldType.SWITCH, identifier: "agree", defaultValue: "{{sourceData.agree}}", }, }, }, array: { fieldType: FieldType.ARRAY, identifier: "array", defaultValue: "{{sourceData.array}}", children: { [ARRAY_ITEM_KEY]: { fieldType: FieldType.OBJECT, identifier: ARRAY_ITEM_KEY, defaultValue: "", children: { field1: { fieldType: FieldType.SWITCH, identifier: "field1", defaultValue: "{{sourceData.field1}}", }, field2: { fieldType: FieldType.DATEPICKER, identifier: "field2", defaultValue: "{{sourceData.field2}}", }, field3: { fieldType: FieldType.DATEPICKER, identifier: "field3", defaultValue: "10/12/2021", }, field4: { fieldType: FieldType.CHECKBOX, identifier: "field4", defaultValue: "{{sourceData.field1}}", }, field5: { fieldType: FieldType.PHONE_NUMBER_INPUT, identifier: "field5", defaultValue: "{{sourceData.field1}}", }, }, }, }, }, }, }, } as unknown as Schema; const expectedPathList = [ `schema.${ROOT_SCHEMA_KEY}.children.dob.defaultValue`, `schema.${ROOT_SCHEMA_KEY}.children.obj.children.agree.defaultValue`, `schema.${ROOT_SCHEMA_KEY}.children.array.children.${ARRAY_ITEM_KEY}.children.field1.defaultValue`, `schema.${ROOT_SCHEMA_KEY}.children.array.children.${ARRAY_ITEM_KEY}.children.field2.defaultValue`, `schema.${ROOT_SCHEMA_KEY}.children.array.children.${ARRAY_ITEM_KEY}.children.field4.defaultValue`, ]; const result = dynamicPropertyPathListFromSchema(schema); expect(result).toEqual(expectedPathList); }); }); describe(".computeSchema", () => { it("returns LIMIT_EXCEEDED state when source data exceeds limit", () => { const sourceData = { number: 10, text: "text", object1: { number: 10, text: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj: { a: 10, c: 20, }, }, }, }, object2: { number: 10, text: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj: { a: 10, c: 20, }, }, }, }, arr2: ["1", "2"], arr1: [ { number: 10, text: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj: { a: 10, c: 20, }, }, }, }, { number1: 10, text2: "text", obj: { arr: { number: 10, text: "text", arr: ["a", "b"], obj1: { a: 10, c: 20, }, }, }, }, ], }; const response = computeSchema({ currSourceData: sourceData, widgetName: "JSONForm1", fieldThemeStylesheets: {} as FieldThemeStylesheet, }); expect(response.status).toEqual(ComputedSchemaStatus.LIMIT_EXCEEDED); expect(response.dynamicPropertyPathList).toBeUndefined(); expect(response.schema).toEqual({}); }); it("returns UNCHANGED status no source data is passed", () => { const inputSourceData = [undefined, {}]; inputSourceData.forEach((sourceData) => { const response = computeSchema({ currSourceData: sourceData, widgetName: "JSONForm1", fieldThemeStylesheets: {} as FieldThemeStylesheet, }); expect(response.status).toEqual(ComputedSchemaStatus.UNCHANGED); expect(response.dynamicPropertyPathList).toBeUndefined(); expect(response.schema).toEqual({}); }); }); it("returns UNCHANGED status when prev and curr source data are same", () => { const currSourceData = { obj: { number: 10, arrayOfString: ["test"], }, string: "test", }; const prevSourceData = { obj: { number: 10, arrayOfString: ["test"], }, string: "test", }; const response = computeSchema({ currSourceData, prevSourceData, widgetName: "JSONForm1", fieldThemeStylesheets: {} as FieldThemeStylesheet, }); expect(response.status).toEqual(ComputedSchemaStatus.UNCHANGED); expect(response.dynamicPropertyPathList).toBeUndefined(); expect(response.schema).toEqual({}); }); it("returns new schema when prevSchema is not provided", () => { const response = computeSchema({ currSourceData: schemaTestData.initialDataset.dataSource, widgetName: "JSONForm1", fieldThemeStylesheets: schemaTestData.fieldThemeStylesheets, }); const expectedDynamicPropertyPathList = [ { key: "schema.__root_schema__.children.dob.defaultValue" }, { key: "schema.__root_schema__.children.boolean.defaultValue" }, ]; expect(response.status).toEqual(ComputedSchemaStatus.UPDATED); expect(response.dynamicPropertyPathList).toEqual( expectedDynamicPropertyPathList, ); expect(response.schema).toEqual(schemaTestData.initialDataset.schemaOutput); }); it("returns retains existing dynamicBindingPropertyPathList", () => { const existingDynamicBindingPropertyPathList = [ { key: "dummy.path1" }, { key: "dummy.path2" }, { key: "sourceData" }, ]; const expectedDynamicPropertyPathList = [ ...existingDynamicBindingPropertyPathList, { key: "schema.__root_schema__.children.dob.defaultValue" }, { key: "schema.__root_schema__.children.boolean.defaultValue" }, ]; const response = computeSchema({ currSourceData: schemaTestData.initialDataset.dataSource, currentDynamicPropertyPathList: existingDynamicBindingPropertyPathList, widgetName: "JSONForm1", fieldThemeStylesheets: schemaTestData.fieldThemeStylesheets, }); expect(response.status).toEqual(ComputedSchemaStatus.UPDATED); expect(response.dynamicPropertyPathList).toEqual( expectedDynamicPropertyPathList, ); expect(response.schema).toEqual(schemaTestData.initialDataset.schemaOutput); }); it("returns updated schema when new key added to existing data source", () => { const existingDynamicBindingPropertyPathList = [ { key: "dummy.path1" }, { key: "dummy.path2" }, { key: "sourceData" }, ]; const expectedDynamicPropertyPathList = [ ...existingDynamicBindingPropertyPathList, { key: "schema.__root_schema__.children.dob.defaultValue" }, ]; const response = computeSchema({ currSourceData: schemaTestData.withRemovedAddedKeyToInitialDataset.dataSource, prevSourceData: schemaTestData.initialDataset.dataSource, prevSchema: schemaTestData.initialDataset.schemaOutput, currentDynamicPropertyPathList: existingDynamicBindingPropertyPathList, widgetName: "JSONForm1", fieldThemeStylesheets: schemaTestData.fieldThemeStylesheets, }); expect(response.status).toEqual(ComputedSchemaStatus.UPDATED); expect(response.dynamicPropertyPathList).toEqual( expectedDynamicPropertyPathList, ); expect(response.schema).toEqual( schemaTestData.withRemovedAddedKeyToInitialDataset.schemaOutput, ); }); });
1,784
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig.test.ts
import type { OnButtonClickProps } from "components/propertyControls/ButtonControl"; import { set } from "lodash"; import { EVALUATION_PATH } from "utils/DynamicBindingUtils"; import schemaTestData from "../schemaTestData"; import { onGenerateFormClick } from "./propertyConfig"; import generatePanelPropertyConfig from "./propertyConfig/generatePanelPropertyConfig"; describe(".generatePanelPropertyConfig", () => { it("ACTION_SELECTOR control field should not have customJSControl and have additionalAutoComplete", (done) => { const panelConfig = generatePanelPropertyConfig(1); panelConfig?.children?.forEach((section) => { if ("sectionName" in section) { section.children?.forEach((property) => { if ("propertyName" in property) { // If property is an event/action if (property.controlType === "ACTION_SELECTOR") { if (property.customJSControl) { done.fail( `${section.sectionName} - ${property.propertyName} should not define "customJSControl" property`, ); } if (!property.additionalAutoComplete) { done.fail( `${section.sectionName} - ${property.propertyName} should define "additionalAutoComplete" property. Use getAutocompleteProperties`, ); } } } }); } }); done(); }); }); describe(".onGenerateFormClick", () => { it("calls batchUpdateProperties with new schema when prevSchema is not provided", () => { const mockBatchUpdateProperties = jest.fn(); const widgetProperties = { autoGenerateForm: false, widgetName: "JSONForm1", childStylesheet: schemaTestData.fieldThemeStylesheets, }; set( widgetProperties, `${EVALUATION_PATH}.evaluatedValues.sourceData`, schemaTestData.initialDataset.dataSource, ); const params = { batchUpdateProperties: mockBatchUpdateProperties, props: { widgetProperties, }, } as unknown as OnButtonClickProps; onGenerateFormClick(params); const expectedDynamicPropertyPathList = [ { key: "schema.__root_schema__.children.dob.defaultValue" }, { key: "schema.__root_schema__.children.boolean.defaultValue" }, ]; expect(mockBatchUpdateProperties.mock.calls.length).toBe(1); const response = mockBatchUpdateProperties.mock.calls[0][0]; expect(response.fieldLimitExceeded).toEqual(false); expect(response.dynamicPropertyPathList).toEqual( expectedDynamicPropertyPathList, ); expect(response.schema).toEqual(schemaTestData.initialDataset.schemaOutput); }); it("calls batchUpdateProperties with retained existing dynamicBindingPropertyPathList", () => { const existingDynamicBindingPropertyPathList = [ { key: "dummy.path1" }, { key: "dummy.path2" }, { key: "sourceData" }, ]; const mockBatchUpdateProperties = jest.fn(); const widgetProperties = { autoGenerateForm: false, widgetName: "JSONForm1", childStylesheet: schemaTestData.fieldThemeStylesheets, dynamicPropertyPathList: existingDynamicBindingPropertyPathList, }; set( widgetProperties, `${EVALUATION_PATH}.evaluatedValues.sourceData`, schemaTestData.initialDataset.dataSource, ); const params = { batchUpdateProperties: mockBatchUpdateProperties, props: { widgetProperties, }, } as unknown as OnButtonClickProps; onGenerateFormClick(params); const expectedDynamicPropertyPathList = [ ...existingDynamicBindingPropertyPathList, { key: "schema.__root_schema__.children.dob.defaultValue" }, { key: "schema.__root_schema__.children.boolean.defaultValue" }, ]; expect(mockBatchUpdateProperties.mock.calls.length).toBe(1); const response = mockBatchUpdateProperties.mock.calls[0][0]; expect(response.fieldLimitExceeded).toEqual(false); expect(response.dynamicPropertyPathList).toEqual( expectedDynamicPropertyPathList, ); expect(response.schema).toEqual(schemaTestData.initialDataset.schemaOutput); }); it("calls batchUpdateProperties with updated schema when new key added to existing data source", () => { const existingDynamicBindingPropertyPathList = [ { key: "dummy.path1" }, { key: "dummy.path2" }, { key: "sourceData" }, ]; const mockBatchUpdateProperties = jest.fn(); const widgetProperties = { autoGenerateForm: false, widgetName: "JSONForm1", childStylesheet: schemaTestData.fieldThemeStylesheets, dynamicPropertyPathList: existingDynamicBindingPropertyPathList, schema: schemaTestData.initialDataset.schemaOutput, }; set( widgetProperties, `${EVALUATION_PATH}.evaluatedValues.sourceData`, schemaTestData.withRemovedAddedKeyToInitialDataset.dataSource, ); const params = { batchUpdateProperties: mockBatchUpdateProperties, props: { widgetProperties, }, } as unknown as OnButtonClickProps; onGenerateFormClick(params); const expectedDynamicPropertyPathList = [ ...existingDynamicBindingPropertyPathList, { key: "schema.__root_schema__.children.dob.defaultValue" }, ]; expect(mockBatchUpdateProperties.mock.calls.length).toBe(1); const response = mockBatchUpdateProperties.mock.calls[0][0]; expect(response.fieldLimitExceeded).toEqual(false); expect(response.dynamicPropertyPathList).toEqual( expectedDynamicPropertyPathList, ); expect(response.schema).toEqual( schemaTestData.withRemovedAddedKeyToInitialDataset.schemaOutput, ); }); });
1,786
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/generatePanelPropertyConfig.test.ts
import type { PropertyPaneControlConfig } from "constants/PropertyControlConstants"; import generatePanelPropertyConfig from "./generatePanelPropertyConfig"; describe(".generatePanelPropertyConfig", () => { it("generates nested panel property config based on level", () => { const level = 2; const result = generatePanelPropertyConfig(level); expect(result).not.toBeUndefined(); let currentLevel = 1; let currentPropertyConfig = result; while (currentLevel <= level) { expect(currentPropertyConfig?.editableTitle).toEqual(true); expect(currentPropertyConfig?.titlePropertyName).toEqual("label"); expect(currentPropertyConfig?.panelIdPropertyName).toEqual("identifier"); const fieldConfigurationProperty = ( currentPropertyConfig?.contentChildren?.[0] .children as PropertyPaneControlConfig[] ).find(({ propertyName }) => propertyName === "children"); expect(fieldConfigurationProperty).not.toBeUndefined(); expect(fieldConfigurationProperty?.label).toEqual("Field configuration"); expect(fieldConfigurationProperty?.controlType).toEqual( "FIELD_CONFIGURATION", ); expect(fieldConfigurationProperty?.hidden).toBeDefined(); currentLevel += 1; currentPropertyConfig = fieldConfigurationProperty?.panelConfig; } }); });
1,788
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/helper.test.ts
import { get, set } from "lodash"; import schemaTestData from "widgets/JSONFormWidget/schemaTestData"; import type { Schema, SchemaItem } from "widgets/JSONFormWidget/constants"; import { ARRAY_ITEM_KEY, DataType, FieldType, } from "widgets/JSONFormWidget/constants"; import type { JSONFormWidgetProps } from ".."; import { fieldTypeUpdateHook, getSchemaItem, getStylesheetValue, hiddenIfArrayItemIsObject, updateChildrenDisabledStateHook, } from "./helper"; import { klona as clone } from "klona/full"; const widgetName = "JSONForm1"; describe(".fieldTypeUpdateHook", () => { it("updates valid new schema item for a field type multiselect -> array", () => { const schema = schemaTestData.initialDataset.schemaOutput; const schemaItemPath = "__root_schema__.children.hobbies"; const propertyPath = `schema.${schemaItemPath}.fieldType`; const fieldType = FieldType.ARRAY; const oldSchemaItem: SchemaItem = get(schema, schemaItemPath); const expectedNewSchemaItem = { isCollapsible: true, isDisabled: false, isRequired: false, isVisible: true, label: "Hobbies", backgroundColor: "#FAFAFA", children: { __array_item__: { isDisabled: false, isRequired: false, label: "Array Item", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "travelling", isCustomField: false, identifier: ARRAY_ITEM_KEY, accessor: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, isSpellCheck: false, position: -1, accentColor: "{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", borderRadius: "{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", boxShadow: "none", labelTextSize: "0.875rem", }, }, dataType: DataType.ARRAY, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.hobbies))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.ARRAY, sourceData: ["travelling", "skating", "off-roading"], isCustomField: false, accessor: "hobbies", identifier: "hobbies", originalIdentifier: "hobbies", position: 4, labelTextSize: "0.875rem", }; const expectedNewSchema = set( clone(schema), schemaItemPath, expectedNewSchemaItem, ); const [result] = fieldTypeUpdateHook( { schema, widgetName, childStylesheet: schemaTestData.fieldThemeStylesheets, } as unknown as JSONFormWidgetProps, propertyPath, fieldType, ) || []; const newSchema: SchemaItem = result.propertyValue; expect(result.propertyPath).toEqual("schema"); expect(oldSchemaItem.fieldType).toEqual(FieldType.MULTISELECT); expect(newSchema).toEqual(expectedNewSchema); }); it("updates valid new schema item for a field type array -> multiselect", () => { const oldSchema = clone(schemaTestData.initialDataset.schemaOutput); const schemaItemPath = "__root_schema__.children.hobbies"; const propertyPath = `schema.${schemaItemPath}.fieldType`; const fieldType = FieldType.MULTISELECT; const oldSchemaItem = { isCollapsible: true, isDisabled: false, isVisible: true, label: "Hobbies", children: { __array_item__: { isDisabled: false, label: "Array Item", isVisible: true, children: {}, dataType: DataType.STRING, defaultValue: undefined, fieldType: FieldType.TEXT_INPUT, iconAlign: "left", sourceData: "travelling", isCustomField: false, accessor: ARRAY_ITEM_KEY, identifier: ARRAY_ITEM_KEY, originalIdentifier: ARRAY_ITEM_KEY, isSpellCheck: false, position: -1, accentColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, }, dataType: DataType.ARRAY, defaultValue: "{{((sourceData, formData, fieldState) => (sourceData.hobbies))(JSONForm1.sourceData, JSONForm1.formData, JSONForm1.fieldState)}}", fieldType: FieldType.ARRAY, sourceData: ["travelling", "skating", "off-roading"], isCustomField: false, name: "hobbies", accessor: "hobbies", identifier: "hobbies", originalIdentifier: "hobbies", position: 4, }; const expectedNewSchema = clone(schemaTestData.initialDataset.schemaOutput); set(oldSchema, "__root_schema__.children.hobbies", oldSchemaItem); const [result] = fieldTypeUpdateHook( { schema: oldSchema, widgetName, childStylesheet: schemaTestData.fieldThemeStylesheets, } as unknown as JSONFormWidgetProps, propertyPath, fieldType, ) || []; const newSchema: SchemaItem = result.propertyValue; expect(result.propertyPath).toEqual("schema"); expect(oldSchemaItem.fieldType).toEqual(FieldType.ARRAY); expect(newSchema).toEqual(expectedNewSchema); }); }); describe(".hiddenIfArrayItemIsObject", () => { it("returns boolean for schemaItem is an array item for field type object or array", () => { const schema = schemaTestData.initialDataset.schemaOutput; const inputs = [ "schema.__root_schema__.children.hobbies.fieldType", "schema.__root_schema__.children.education", "schema.__root_schema__.children.education.children.__array_item__.defaultValue", ]; const expectedOutput = [false, false, true]; inputs.forEach((input, index) => { const result = hiddenIfArrayItemIsObject( { schema, } as unknown as JSONFormWidgetProps, input, ); expect(result).toEqual(expectedOutput[index]); }); }); it("returns boolean for schemaItem is an array item for field type object or array with checkGrandParentPath options", () => { const schema = schemaTestData.initialDataset.schemaOutput; const inputs = [ "schema.__root_schema__.children.hobbies.fieldType", "schema.__root_schema__.children.education", "schema.__root_schema__.children.education.children.__array_item__.children.age", ]; const expectedOutput = [false, false, true]; inputs.forEach((input, index) => { const result = hiddenIfArrayItemIsObject( { schema, } as unknown as JSONFormWidgetProps, input, { checkGrandParentPath: true, }, ); expect(result).toEqual(expectedOutput[index]); }); }); }); describe(".getSchemaItem", () => { it("returns matchers", () => { const schema = schemaTestData.initialDataset.schemaOutput; const propertyPath = "schema.__root_schema__.children.hobbies.fieldType"; const result = getSchemaItem( { schema, } as unknown as JSONFormWidgetProps, propertyPath, ); expect(result.fieldTypeMatches).toBeDefined(); expect(result.fieldTypeNotMatches).toBeDefined(); expect(result.fieldTypeNotIncludes).toBeDefined(); expect(result.compute).toBeDefined(); }); it("returns boolean when fieldTypeMatches is chained", () => { const schema = schemaTestData.initialDataset.schemaOutput; const propertyPath = "schema.__root_schema__.children.hobbies.fieldType"; const inputs = [ FieldType.NUMBER_INPUT, FieldType.ARRAY, FieldType.MULTISELECT, ]; const expectedOutput = [false, false, true]; inputs.forEach((input, index) => { const result = getSchemaItem( { schema, } as unknown as JSONFormWidgetProps, propertyPath, ).fieldTypeMatches(input); expect(result).toEqual(expectedOutput[index]); }); }); it("returns boolean when fieldTypeNotMatches is chained", () => { const schema = schemaTestData.initialDataset.schemaOutput; const propertyPath = "schema.__root_schema__.children.hobbies.fieldType"; const inputs = [ FieldType.NUMBER_INPUT, FieldType.ARRAY, FieldType.MULTISELECT, ]; const expectedOutput = [true, true, false]; inputs.forEach((input, index) => { const result = getSchemaItem( { schema, } as unknown as JSONFormWidgetProps, propertyPath, ).fieldTypeNotMatches(input); expect(result).toEqual(expectedOutput[index]); }); }); it("returns boolean when fieldTypeNotIncludes is chained", () => { const schema = schemaTestData.initialDataset.schemaOutput; const propertyPath = "schema.__root_schema__.children.hobbies.fieldType"; const inputs = [ [FieldType.NUMBER_INPUT, FieldType.ARRAY, FieldType.MULTISELECT], [FieldType.SWITCH, FieldType.DATEPICKER], ]; const expectedOutput = [false, true]; inputs.forEach((input, index) => { const result = getSchemaItem( { schema, } as unknown as JSONFormWidgetProps, propertyPath, ).fieldTypeNotIncludes(input); expect(result).toEqual(expectedOutput[index]); }); }); it("returns any value returned from the callback passed to the .then method", () => { const schema = schemaTestData.initialDataset.schemaOutput; const propertyPath = "schema.__root_schema__.children.hobbies.fieldType"; const expectedOutput = get(schema, "__root_schema__.children.hobbies"); const result = getSchemaItem( { schema, } as unknown as JSONFormWidgetProps, propertyPath, ).compute((schemaItem) => schemaItem); expect(result).toEqual(expectedOutput); }); }); describe(".updateChildrenDisabledStateHook", () => { it("recursively updates isDisabled of all it's children", () => { const schema = schemaTestData.initialDataset.schemaOutput; const propertyPath = "schema.__root_schema__.children.education.isDisabled"; const isDisabled = true; const oldSchema: Schema = get( schema, "__root_schema__.children.education.children", ); const [result] = updateChildrenDisabledStateHook( { schema, } as unknown as JSONFormWidgetProps, propertyPath, isDisabled, ) || []; const updatedSchema: Schema = result.propertyValue; expect(result.propertyPath); expect(oldSchema.__array_item__.children.college.isDisabled).toEqual(false); expect(oldSchema.__array_item__.children.number.isDisabled).toEqual(false); expect(oldSchema.__array_item__.children.graduationDate.isDisabled).toEqual( false, ); expect(oldSchema.__array_item__.children.boolean.isDisabled).toEqual(false); expect(updatedSchema.__array_item__.children.college.isDisabled).toEqual( true, ); expect(updatedSchema.__array_item__.children.number.isDisabled).toEqual( true, ); expect( updatedSchema.__array_item__.children.graduationDate.isDisabled, ).toEqual(true); expect(updatedSchema.__array_item__.children.boolean.isDisabled).toEqual( true, ); }); }); describe(".getStylesheetValue", () => { it("returns valid stylesheet value", () => { const props = { widgetName: "Form1", schema: schemaTestData.initialDataset.schemaOutput, } as unknown as JSONFormWidgetProps; const inputAndExpectedOutput = [ ["", ""], ["schema.__root_schema__.children.education.isDisabled", ""], [ "schema.__root_schema__.children.name.borderRadius", "{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(Form1.sourceData, Form1.formData, Form1.fieldState)}}", ], ["schema", ""], ]; inputAndExpectedOutput.forEach(([input, expectedOutput]) => { const result = getStylesheetValue(props, input, { childStylesheet: schemaTestData.fieldThemeStylesheets, } as any); expect(result).toEqual(expectedOutput); }); }); });
1,797
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/multiselect.test.ts
import _ from "lodash"; import type { JSONFormWidgetProps } from "../.."; import { defaultOptionValueValidation } from "./multiSelect"; describe(".defaultOptionValueValidation", () => { it("return undefined when input is undefined", () => { const input = undefined; const expectedOutput = { isValid: true, parsed: undefined, messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return null when input is null", () => { const input = null; const expectedOutput = { isValid: true, parsed: null, messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return undefined with empty string", () => { const input = ""; const expectedOutput = { isValid: true, parsed: undefined, messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return value with array of string", () => { const input = ["green", "red"]; const expectedOutput = { isValid: true, parsed: ["green", "red"], messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return value with csv", () => { const input = "green, red"; const expectedOutput = { isValid: true, parsed: ["green", "red"], messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return value with stringified array of string", () => { const input = `["green", "red"]`; const expectedOutput = { isValid: true, parsed: ["green", "red"], messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return value with stringified array json", () => { const input = `[ { "label": "green", "value": "green" }, { "label": "red", "value": "red" } ]`; const expectedOutput = { isValid: true, parsed: [ { label: "green", value: "green", }, { label: "red", value: "red", }, ], messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("should return isValid false with invalid values", () => { const inputAndExpectedOutput = [ [ true, { isValid: false, parsed: [], messages: [ { name: "TypeError", message: "value should match: Array<string | number> | Array<{label: string, value: string | number}>", }, ], }, ], [ {}, { isValid: false, parsed: [], messages: [ { name: "TypeError", message: "value should match: Array<string | number> | Array<{label: string, value: string | number}>", }, ], }, ], [ [undefined], { isValid: false, parsed: [], messages: [ { name: "TypeError", message: "value should match: Array<string | number> | Array<{label: string, value: string | number}>", }, ], }, ], [ [true], { isValid: false, parsed: [], messages: [ { name: "TypeError", message: "value should match: Array<string | number> | Array<{label: string, value: string | number}>", }, ], }, ], [ ["green", "green"], { isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "value must be unique. Duplicate values found", }, ], }, ], [ [ { label: "green", value: "green", }, { label: "green", value: "green", }, ], { isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "value must be unique. Duplicate values found", }, ], }, ], [ [ { label: "green", }, { label: "green", }, ], { isValid: false, parsed: [], messages: [ { name: "TypeError", message: "value should match: Array<string | number> | Array<{label: string, value: string | number}>", }, ], }, ], [ [ { label: "green", value: "green", }, "blue", ], { isValid: false, parsed: [], messages: [ { name: "TypeError", message: "value should match: Array<string | number> | Array<{label: string, value: string | number}>", }, ], }, ], ]; inputAndExpectedOutput.forEach(([input, expected]) => { const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expected); }); }); });
1,799
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/radioGroup.test.ts
import _ from "lodash"; import type { JSONFormWidgetProps } from "../.."; import { optionsValidation } from "./radioGroup"; /** * Note: If this test fails then it is an indication than the JSONForm * radio group field options validation doesn't comply with the radio group * widget's options validation due to the changes in the validation function. * Appropriates fixes has to be made in order for both the widgets to work. * * The above might not always be true but double checking never hurts. */ describe(".optionsValidation", () => { it("returns invalid when values are duplicate", () => { const input = [ { label: "A", value: "A" }, { label: "B", value: "A" }, ]; const expectedOutput = { isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "path:value must be unique. Duplicate values found", }, ], }; const response = optionsValidation(input, {} as JSONFormWidgetProps, _); expect(response).toEqual(expectedOutput); }); it("returns invalid when label is missing", () => { const input = [{ value: "A" }, { label: "B", value: "A" }]; const expectedOutput = { isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "Invalid entry at index: 0. Missing required key: label", }, ], }; const response = optionsValidation(input, {} as JSONFormWidgetProps, _); expect(response).toEqual(expectedOutput); }); it("returns invalid when value has mix types", () => { const input = [ { label: "A", value: "A" }, { label: "B", value: 2 }, ]; const expectedOutput = { isValid: false, parsed: [], messages: [ { name: "TypeError", message: "All value properties in options must have the same type", }, ], }; const response = optionsValidation(input, {} as JSONFormWidgetProps, _); expect(response).toEqual(expectedOutput); }); it("returns invalid when value has null or undefined", () => { const inputs = [ [ { label: "A", value: null }, { label: "B", value: null }, ], [ { label: "A", value: undefined }, { label: "B", value: undefined }, ], ]; const expectedOutput = { isValid: false, parsed: [], messages: [ { name: "TypeError", message: 'This value does not evaluate to type Array<{ "label": "string", "value": "string" | number }>', }, ], }; inputs.forEach((input) => { const response = optionsValidation(input, {} as JSONFormWidgetProps, _); expect(response).toEqual(expectedOutput); }); }); it("returns valid with valid options", () => { const inputs = [ [ { label: "A", value: "A" }, { label: "B", value: "B" }, ], [ { label: "A", value: 1 }, { label: "B", value: 2 }, ], ]; inputs.forEach((input) => { const response = optionsValidation(input, {} as JSONFormWidgetProps, _); const expectedOutput = { isValid: true, parsed: input, messages: [{ name: "", message: "" }], }; expect(response).toEqual(expectedOutput); }); }); });
1,801
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.test.ts
import _ from "lodash"; import type { JSONFormWidgetProps } from "../.."; import { defaultOptionValueValidation } from "./select"; describe(".defaultOptionValueValidation", () => { it("return undefined when input is undefined", () => { const input = undefined; const expectedOutput = { isValid: true, parsed: undefined, messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return null when input is null", () => { const input = null; const expectedOutput = { isValid: true, parsed: null, messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return empty string with empty string", () => { const input = ""; const expectedOutput = { isValid: true, parsed: "", messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return value with string", () => { const input = "green"; const expectedOutput = { isValid: true, parsed: "green", messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("return value with stringified json", () => { const input = ` { "label": "green", "value": "green" } `; const expectedOutput = { isValid: true, parsed: { label: "green", value: "green", }, messages: [{ name: "", message: "" }], }; const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expectedOutput); }); it("should return isValid false with invalid values", () => { const inputAndExpectedOutput = [ [ true, { isValid: false, parsed: {}, messages: [ { name: "TypeError", message: 'value should match: string | { "label": "label1", "value": "value1" }', }, ], }, ], [ {}, { isValid: false, parsed: {}, messages: [ { name: "TypeError", message: 'value should match: string | { "label": "label1", "value": "value1" }', }, ], }, ], [ [ { label: "green", value: "green", }, "blue", ], { isValid: false, parsed: {}, messages: [ { name: "TypeError", message: 'value should match: string | { "label": "label1", "value": "value1" }', }, ], }, ], [ { label: "green", }, { isValid: false, parsed: {}, messages: [ { name: "TypeError", message: 'value should match: string | { "label": "label1", "value": "value1" }', }, ], }, ], [ { value: "green", }, { isValid: false, parsed: {}, messages: [ { name: "TypeError", message: 'value should match: string | { "label": "label1", "value": "value1" }', }, ], }, ], [ {}, { isValid: false, parsed: {}, messages: [ { name: "TypeError", message: 'value should match: string | { "label": "label1", "value": "value1" }', }, ], }, ], [ [], { isValid: false, parsed: {}, messages: [ { name: "TypeError", message: 'value should match: string | { "label": "label1", "value": "value1" }', }, ], }, ], ]; inputAndExpectedOutput.forEach(([input, expected]) => { const response = defaultOptionValueValidation( input, {} as JSONFormWidgetProps, _, ); expect(response).toEqual(expected); }); }); });
1,811
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ListWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ListWidget/widget/index.test.tsx
import type { AutocompletionDefinitions } from "WidgetProvider/constants"; import ListWidget from "."; import type { WidgetProps } from "widgets/BaseWidget"; describe("Autocomplete suggestions test", () => { it("lists the right autocomplete suggestions", () => { const listWidgetProps: WidgetProps = { widgetId: "yolo", widgetName: "List1", parentId: "123", renderMode: "CANVAS", text: "yo", type: "INPUT_WIDGET_V2", parentColumnSpace: 1, parentRowSpace: 2, leftColumn: 2, rightColumn: 3, topRow: 1, bottomRow: 2, isLoading: false, version: 1, selectedItem: { id: 1, name: "Some random name", }, }; const output = { "!doc": "Containers are used to group widgets together to form logical higher order widgets. Containers let you organize your page better and move all the widgets inside them together.", "!url": "https://docs.appsmith.com/widget-reference/list", backgroundColor: { "!type": "string", "!url": "https://docs.appsmith.com/widget-reference/how-to-use-widgets", }, isVisible: { "!type": "bool", "!doc": "Boolean value indicating if the widget is in visible state", }, selectedItem: { id: "number", name: "string" }, gridGap: "number", items: "?", listData: "?", pageNo: "?", pageSize: "?", }; const autocompleteDefinitions: AutocompletionDefinitions = ListWidget.getAutocompleteDefinitions(); if (typeof autocompleteDefinitions === "function") { expect(autocompleteDefinitions(listWidgetProps)).toStrictEqual(output); } }); });
1,815
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ListWidgetV2/MetaWidgetGenerator.test.ts
import { difference } from "lodash"; import { klona } from "klona"; import type { ConstructorProps, GeneratorOptions } from "./MetaWidgetGenerator"; import MetaWidgetGenerator from "./MetaWidgetGenerator"; import type { FlattenedWidgetProps } from "WidgetProvider/constants"; import { nestedListInput, simpleListInput } from "./testData"; import { RenderModes } from "constants/WidgetConstants"; import { ButtonFactory } from "test/factories/Widgets/ButtonFactory"; import type { LevelData } from "./widget"; import ImageWidget from "widgets/ImageWidget"; import TextWidget from "widgets/TextWidget"; import ListWidget from "widgets/ListWidgetV2"; import CanvasWidget from "widgets/CanvasWidget"; import ContainerWidget from "widgets/ContainerWidget"; import { registerWidgets } from "WidgetProvider/factory/registrationHelper"; interface Validator { widgetType: string; occurrence: number; } interface InitProps { optionsProps?: Partial<GeneratorOptions>; constructorProps?: Partial<ConstructorProps>; passedCache?: Cache; listWidgetId?: string; } const data = [ { id: 1, name: "Blue" }, { id: 2, name: "Pink" }, { id: 3, name: "Black" }, { id: 4, name: "White" }, ]; const DEFAULT_OPTIONS = { cacheIndexArr: [-1, -1], containerParentId: simpleListInput.containerParentId, containerWidgetId: simpleListInput.mainContainerId, currTemplateWidgets: simpleListInput.templateWidgets, data, itemSpacing: 8, infiniteScroll: false, levelData: undefined, prevTemplateWidgets: {}, primaryKeys: data.map((d) => d.id.toString()), scrollElement: null, templateHeight: 120, widgetName: "List1", pageNo: 1, pageSize: 2, serverSidePagination: false, }; const levelData: LevelData = { level_1: { currentIndex: 0, currentItem: "{{List1.listData[0]}}", currentRowCache: { Image1: { entityDefinition: "image: Image1.image,isVisible: Image1.isVisible", rowIndex: 0, metaWidgetId: "623fj7t7ld", metaWidgetName: "Image1", viewIndex: 0, templateWidgetId: "623fj7t7ld", templateWidgetName: "Image1", type: "IMAGE_WIDGET", }, Text1: { entityDefinition: "isVisible: Text1.isVisible,text: Text1.text", rowIndex: 0, metaWidgetId: "9qcijo7ri3", metaWidgetName: "Text1", viewIndex: 0, templateWidgetId: "9qcijo7ri3", templateWidgetName: "Text1", type: "TEXT_WIDGET", }, Text2: { entityDefinition: "isVisible: Text2.isVisible,text: Text2.text", rowIndex: 0, metaWidgetId: "25x15bnona", metaWidgetName: "Text2", viewIndex: 0, templateWidgetId: "25x15bnona", templateWidgetName: "Text2", type: "TEXT_WIDGET", }, List6: { entityDefinition: "backgroundColor: List6.backgroundColor,isVisible: List6.isVisible,itemSpacing: List6.itemSpacing,selectedItem: List6.selectedItem,triggeredItem: List6.triggeredItem,selectedItemView: List6.selectedItemView,triggeredItemView: List6.triggeredItemView,listData: List6.listData,pageNo: List6.pageNo,pageSize: List6.pageSize", rowIndex: 0, metaWidgetId: "fs2d2lqjgd", metaWidgetName: "List6", viewIndex: 0, templateWidgetId: "fs2d2lqjgd", templateWidgetName: "List6", type: "LIST_WIDGET_V2", }, Canvas2: { entityDefinition: "", rowIndex: 0, metaWidgetId: "qpgtpiw3cu", metaWidgetName: "Canvas2", viewIndex: 0, templateWidgetId: "qpgtpiw3cu", templateWidgetName: "Canvas2", type: "CANVAS_WIDGET", }, Container1: { entityDefinition: "backgroundColor: Container1.backgroundColor,isVisible: Container1.isVisible", rowIndex: 0, metaWidgetId: "lneohookgm", metaWidgetName: "Container1", viewIndex: 0, templateWidgetId: "lneohookgm", templateWidgetName: "Container1", type: "CONTAINER_WIDGET", }, }, autocomplete: { currentItem: { id: 1, name: "Blue", }, currentView: "{{Container1.data}}", }, }, }; class Cache { data: Record<string, any> = {}; refData = {}; getWidgetCache = (widgetId: string) => { return this.data[widgetId]; }; setWidgetCache = (widgetId: string, data: any) => { this.data[widgetId] = klona(data); }; setWidgetReferenceCache = (data: any) => { this.refData = data; }; getWidgetReferenceCache = () => { return this.refData; }; } const init = ({ constructorProps, listWidgetId = "DEFAULT_LIST_ID", optionsProps, passedCache, }: InitProps = {}) => { const options = klona({ ...DEFAULT_OPTIONS, ...optionsProps, }); const cache = passedCache || new Cache(); const generator = new MetaWidgetGenerator({ getWidgetCache: () => cache.getWidgetCache(listWidgetId), setWidgetCache: (data) => cache.setWidgetCache(listWidgetId, data), infiniteScroll: false, isListCloned: false, level: 1, onVirtualListScroll: jest.fn, primaryWidgetType: "LIST_WIDGET_V2", renderMode: RenderModes.CANVAS, prefixMetaWidgetId: "test", setWidgetReferenceCache: cache.setWidgetReferenceCache, getWidgetReferenceCache: cache.getWidgetReferenceCache, ...constructorProps, }); const initialResult = generator.withOptions(options).generate(); options.prevTemplateWidgets = options.currTemplateWidgets; return { options, generator, cache, initialResult, }; }; const validateMetaWidgetType = ( metaWidgets: Record<string, FlattenedWidgetProps>, validators: Validator[], ) => { const maxMetaWidgets = Object.keys(metaWidgets).length; const maxExpectedWidgets = validators.reduce((acc, validator) => { acc += validator.occurrence; return acc; }, 0); expect(maxMetaWidgets).toEqual(maxExpectedWidgets); const generatedMetaWidgetTypes = Object.values(metaWidgets).map( (w) => w.type, ); const expectedWidgetTypes = validators.reduce((acc: string[], validator) => { const { occurrence, widgetType } = validator; acc = [...acc, ...Array(occurrence).fill(widgetType)]; return acc; }, []); const missingMetaWidget = difference( expectedWidgetTypes, generatedMetaWidgetTypes, ); const extraGeneratedMetaWidgets = difference( generatedMetaWidgetTypes, expectedWidgetTypes, ); expect(missingMetaWidget).toEqual([]); expect(extraGeneratedMetaWidgets).toEqual([]); }; beforeAll(() => { registerWidgets([ ImageWidget, TextWidget, ListWidget, CanvasWidget, ContainerWidget, ]); }); describe("#generate", () => { it("generates meta widgets for first instance", () => { const { initialResult } = init(); const expectedGeneratedCount = 12; const expectedRemovedCount = 0; const { metaWidgets, removedMetaWidgetIds } = initialResult; const metaWidgetsCount = Object.keys(metaWidgets).length; expect(metaWidgetsCount).toEqual(expectedGeneratedCount); expect(removedMetaWidgetIds.length).toEqual(expectedRemovedCount); validateMetaWidgetType(metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 2, }, { widgetType: "CONTAINER_WIDGET", occurrence: 2, }, { widgetType: "IMAGE_WIDGET", occurrence: 2, }, { widgetType: "TEXT_WIDGET", occurrence: 4, }, { widgetType: "INPUT_WIDGET_V2", occurrence: 2, }, ]); }); it("re-generates meta widgets data change", () => { const { generator, options } = init(); const newData = [ { id: 2, name: "Pink" }, { id: 3, name: "Black" }, { id: 4, name: "White" }, ]; options.data = newData; options.primaryKeys = newData.map((d) => d.id.toString()); const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(12); expect(result.removedMetaWidgetIds.length).toEqual(6); validateMetaWidgetType(result.metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 2, }, { widgetType: "CONTAINER_WIDGET", occurrence: 2, }, { widgetType: "IMAGE_WIDGET", occurrence: 2, }, { widgetType: "TEXT_WIDGET", occurrence: 4, }, { widgetType: "INPUT_WIDGET_V2", occurrence: 2, }, ]); }); it("does not re-generates meta widgets when options don't change", () => { const { generator, options } = init(); const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(0); expect(result.removedMetaWidgetIds.length).toEqual(0); }); it("re-generates meta widgets when template widgets change", () => { const { generator, options } = init(); const buttonWidget = ButtonFactory.build(); const containerCanvas = klona( simpleListInput.templateWidgets[simpleListInput.mainContainerCanvasId], ); containerCanvas.children?.push(buttonWidget.widgetId); // Added new widget const nextTemplateWidgets1 = { ...options.currTemplateWidgets, [containerCanvas.widgetId]: containerCanvas, [buttonWidget.widgetId]: buttonWidget, }; options.currTemplateWidgets = nextTemplateWidgets1; const result1 = generator.withOptions(options).generate(); const count1 = Object.keys(result1.metaWidgets).length; expect(count1).toEqual(6); expect(result1.removedMetaWidgetIds.length).toEqual(0); validateMetaWidgetType(result1.metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 2, }, { widgetType: "CONTAINER_WIDGET", occurrence: 2, }, { widgetType: "BUTTON_WIDGET", occurrence: 2, }, ]); // Removed 2 widgets const newContainerCanvas = klona(containerCanvas); const buttonWidgetId = buttonWidget.widgetId; const imageWidgetId = "epowimtfiu"; const removedWidgetIds = [buttonWidgetId, imageWidgetId]; newContainerCanvas.children = newContainerCanvas.children?.filter( (c) => !removedWidgetIds.includes(c), ); const nextTemplateWidget2 = { ...options.currTemplateWidgets, [newContainerCanvas.widgetId]: newContainerCanvas, }; delete nextTemplateWidget2[buttonWidget.widgetId]; delete nextTemplateWidget2["epowimtfiu"]; // Image widget options.currTemplateWidgets = nextTemplateWidget2; const result2 = generator.withOptions(options).generate(); const count2 = Object.keys(result2.metaWidgets).length; expect(count2).toEqual(4); expect(result2.removedMetaWidgetIds.length).toEqual(4); validateMetaWidgetType(result2.metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 2, }, { widgetType: "CONTAINER_WIDGET", occurrence: 2, }, ]); }); it("re-generates meta widgets when page no changes in edit mode", () => { const { generator, options } = init(); options.pageNo = 2; const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(12); expect(result.removedMetaWidgetIds.length).toEqual(6); validateMetaWidgetType(result.metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 2, }, { widgetType: "CONTAINER_WIDGET", occurrence: 2, }, { widgetType: "IMAGE_WIDGET", occurrence: 2, }, { widgetType: "TEXT_WIDGET", occurrence: 4, }, { widgetType: "INPUT_WIDGET_V2", occurrence: 2, }, ]); }); it("re-generates meta widgets when page no changes in view mode", () => { const { generator, options } = init({ constructorProps: { renderMode: RenderModes.PAGE }, }); options.pageNo = 2; const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(12); expect(result.removedMetaWidgetIds.length).toEqual(12); validateMetaWidgetType(result.metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 2, }, { widgetType: "CONTAINER_WIDGET", occurrence: 2, }, { widgetType: "IMAGE_WIDGET", occurrence: 2, }, { widgetType: "TEXT_WIDGET", occurrence: 4, }, { widgetType: "INPUT_WIDGET_V2", occurrence: 2, }, ]); }); it("generates only extra meta widgets when page size increases", () => { const { generator, options } = init(); options.pageSize = 3; const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(6); expect(result.removedMetaWidgetIds.length).toEqual(0); validateMetaWidgetType(result.metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 1, }, { widgetType: "CONTAINER_WIDGET", occurrence: 1, }, { widgetType: "IMAGE_WIDGET", occurrence: 1, }, { widgetType: "TEXT_WIDGET", occurrence: 2, }, { widgetType: "INPUT_WIDGET_V2", occurrence: 1, }, ]); }); it("removes meta widgets when page size decreases", () => { const { generator, options } = init(); options.pageSize = 3; generator.withOptions(options).generate(); options.pageSize = 1; const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(0); expect(result.removedMetaWidgetIds.length).toEqual(12); validateMetaWidgetType(result.metaWidgets, []); }); it("re-generates all meta widgets when primary keys changes in page > 1", () => { const { generator, options } = init({ optionsProps: { pageNo: 2 } }); options.primaryKeys = options.primaryKeys.map((i) => i + "100"); const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(12); expect(result.removedMetaWidgetIds.length).toEqual(6); validateMetaWidgetType(result.metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 2, }, { widgetType: "CONTAINER_WIDGET", occurrence: 2, }, { widgetType: "IMAGE_WIDGET", occurrence: 2, }, { widgetType: "TEXT_WIDGET", occurrence: 4, }, { widgetType: "INPUT_WIDGET_V2", occurrence: 2, }, ]); }); it("re-generates non template meta widgets when primary keys changes in page = 1", () => { const { generator, options } = init(); options.primaryKeys = options.primaryKeys.map((i) => i + "100"); const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; // template and non template meta widgets will update expect(count).toEqual(12); // non template meta widgets will get removed expect(result.removedMetaWidgetIds.length).toEqual(6); validateMetaWidgetType(result.metaWidgets, [ { widgetType: "CANVAS_WIDGET", occurrence: 2, }, { widgetType: "CONTAINER_WIDGET", occurrence: 2, }, { widgetType: "IMAGE_WIDGET", occurrence: 2, }, { widgetType: "TEXT_WIDGET", occurrence: 4, }, { widgetType: "INPUT_WIDGET_V2", occurrence: 2, }, ]); }); it("doesn't re-generates meta widgets when only serverSizePagination is toggled while other options remains the same", () => { const listData = data.slice(0, 2); const { generator, options } = init({ optionsProps: { data: listData } }); options.serverSidePagination = true; const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(0); expect(result.removedMetaWidgetIds.length).toEqual(0); }); it("doesn't re-generates meta widgets when templateHeight changes", () => { const { generator, options } = init(); options.templateHeight += 1000; const result = generator.withOptions(options).generate(); const count = Object.keys(result.metaWidgets).length; expect(count).toEqual(0); expect(result.removedMetaWidgetIds.length).toEqual(0); }); it("disables widget operations non template rows", () => { const { initialResult } = init({ optionsProps: { pageSize: 3 } }); const templateWidgetIds = Object.keys(simpleListInput.templateWidgets); const count = Object.keys(initialResult.metaWidgets).length; expect(count).toEqual(18); Object.values(initialResult.metaWidgets).forEach((metaWidget) => { if (!templateWidgetIds.includes(metaWidget.widgetId)) { expect(metaWidget.resizeDisabled).toEqual(true); expect(metaWidget.disablePropertyPane).toEqual(true); expect(metaWidget.dragDisabled).toEqual(true); expect(metaWidget.dropDisabled).toEqual(true); expect(metaWidget.ignoreCollision).toEqual(true); expect(metaWidget.shouldScrollContents).toEqual(undefined); expect(metaWidget.disabledResizeHandles).toEqual([ "left", "top", "right", "bottomRight", "topLeft", "topRight", "bottomLeft", ]); } }); }); it("widget operations enabled on template row", () => { const { initialResult } = init(); const templateWidgetIds = Object.keys(simpleListInput.templateWidgets); Object.values(initialResult.metaWidgets).forEach((metaWidget) => { if (templateWidgetIds.includes(metaWidget.widgetId)) { expect(metaWidget.resizeDisabled).toEqual(undefined); expect(metaWidget.disablePropertyPane).toEqual(undefined); expect(metaWidget.dropDisabled).toEqual(undefined); expect(metaWidget.ignoreCollision).toEqual(undefined); if (metaWidget.type === "CONTAINER_WIDGET") { expect(metaWidget.dragDisabled).toEqual(true); expect(metaWidget.disabledResizeHandles).toEqual([ "left", "top", "right", "bottomRight", "topLeft", "topRight", "bottomLeft", ]); } else { expect(metaWidget.disabledResizeHandles).toEqual(undefined); } } }); }); it("generates till it finds a nested list and not beyond that", () => { const { initialResult } = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, }, }); const count = Object.keys(initialResult.metaWidgets).length; expect(count).toEqual(12); expect(initialResult.removedMetaWidgetIds.length).toEqual(0); }); it("adds LevelData to nested list", () => { const { initialResult } = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, }, }); const expectedLevelData = { level_1: { currentIndex: 0, currentItem: "{{List1.listData[0]}}", currentRowCache: { Image1: { entityDefinition: "image: Image1.image,isVisible: Image1.isVisible", rowIndex: 0, metaWidgetId: "623fj7t7ld", metaWidgetName: "Image1", viewIndex: 0, templateWidgetId: "623fj7t7ld", templateWidgetName: "Image1", type: "IMAGE_WIDGET", }, Text1: { entityDefinition: "isVisible: Text1.isVisible,text: Text1.text", rowIndex: 0, metaWidgetId: "9qcijo7ri3", metaWidgetName: "Text1", viewIndex: 0, templateWidgetId: "9qcijo7ri3", templateWidgetName: "Text1", type: "TEXT_WIDGET", }, Text2: { entityDefinition: "isVisible: Text2.isVisible,text: Text2.text", rowIndex: 0, metaWidgetId: "25x15bnona", metaWidgetName: "Text2", viewIndex: 0, templateWidgetId: "25x15bnona", templateWidgetName: "Text2", type: "TEXT_WIDGET", }, List6: { entityDefinition: "backgroundColor: List6.backgroundColor,isVisible: List6.isVisible,itemSpacing: List6.itemSpacing,selectedItem: List6.selectedItem,selectedItemView: List6.selectedItemView,triggeredItem: List6.triggeredItem,triggeredItemView: List6.triggeredItemView,listData: List6.listData,pageNo: List6.pageNo,pageSize: List6.pageSize,currentItemsView: List6.currentItemsView", rowIndex: 0, metaWidgetId: "fs2d2lqjgd", metaWidgetName: "List6", viewIndex: 0, templateWidgetId: "fs2d2lqjgd", templateWidgetName: "List6", type: "LIST_WIDGET_V2", }, Canvas1: {}, Canvas2: { entityDefinition: "", rowIndex: 0, metaWidgetId: "qpgtpiw3cu", metaWidgetName: "Canvas2", viewIndex: 0, templateWidgetId: "qpgtpiw3cu", templateWidgetName: "Canvas2", type: "CANVAS_WIDGET", }, Container1: { entityDefinition: "backgroundColor: Container1.backgroundColor,isVisible: Container1.isVisible", rowIndex: 0, metaWidgetId: "lneohookgm", metaWidgetName: "Container1", viewIndex: 0, templateWidgetId: "lneohookgm", templateWidgetName: "Container1", type: "CONTAINER_WIDGET", }, }, autocomplete: { currentItem: { id: 1, name: "Blue", }, currentView: `{{((data, blackListArr) => { const newObj = {}; for (const key in data) { if (data.hasOwnProperty(key) && typeof data[key] === 'object') { newObj[key] = Object.fromEntries( Object.entries(data[key]).filter( ([nestedKey]) => !blackListArr.includes(nestedKey) ) ); } } return newObj; })(Container1.data, [\"selectedItemView\",\"triggeredItemView\",\"currentItemsView\"] ) }}`, }, }, }; const nestedListWidgetId = "fs2d2lqjgd"; const metaListWidget = initialResult.metaWidgets[nestedListWidgetId]; Object.values(initialResult.metaWidgets).forEach((metaWidget) => { if (metaWidget.type === "LIST_WIDGET_V2") { expect(metaWidget.level).toEqual(2); } }); expect(metaListWidget.levelData).toEqual(expectedLevelData); }); it("generates meta widgets for nestedList widget", () => { const nestedListWidgetId = "fs2d2lqjgd"; const nestedListWidget = nestedListInput.templateWidgets[nestedListWidgetId]; const cache = new Cache(); const generator = new MetaWidgetGenerator({ getWidgetCache: () => cache.getWidgetCache(nestedListWidgetId), setWidgetCache: (data) => cache.setWidgetCache(nestedListWidgetId, data), getWidgetReferenceCache: cache.getWidgetReferenceCache, setWidgetReferenceCache: cache.setWidgetReferenceCache, infiniteScroll: false, prefixMetaWidgetId: "test", isListCloned: false, level: 2, onVirtualListScroll: jest.fn, primaryWidgetType: "LIST_WIDGET_V2", renderMode: RenderModes.CANVAS, }); const initialResult = generator .withOptions({ ...DEFAULT_OPTIONS, currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListWidget.mainCanvasId, containerWidgetId: nestedListWidget.mainContainerId, levelData, pageSize: 3, widgetName: "List6", }) .generate(); const count = Object.keys(initialResult.metaWidgets).length; expect(count).toEqual(15); expect(initialResult.removedMetaWidgetIds.length).toEqual(0); }); it("removed BlackListed properties from Parent InnerList", () => { const nestedTextWidgetId = "dkk5yh9urt"; const nestedListWidgetId = "fs2d2lqjgd"; const nestedListWidget = nestedListInput.templateWidgets[nestedListWidgetId]; const cache = new Cache(); const generator = new MetaWidgetGenerator({ getWidgetCache: () => cache.getWidgetCache(nestedListWidgetId), setWidgetCache: (data) => cache.setWidgetCache(nestedListWidgetId, data), getWidgetReferenceCache: cache.getWidgetReferenceCache, setWidgetReferenceCache: cache.setWidgetReferenceCache, infiniteScroll: false, prefixMetaWidgetId: "test", isListCloned: false, level: 2, onVirtualListScroll: jest.fn, primaryWidgetType: "LIST_WIDGET_V2", renderMode: RenderModes.CANVAS, }); const initialResult = generator .withOptions({ ...DEFAULT_OPTIONS, currTemplateWidgets: { ...nestedListInput.templateWidgets, dkk5yh9urt: { ...nestedListInput.templateWidgets[nestedTextWidgetId], text: "{{level_1.currentView.List6}}", }, }, containerParentId: nestedListWidget.mainCanvasId, containerWidgetId: nestedListWidget.mainContainerId, levelData, pageSize: 3, widgetName: "List6", }) .generate(); const expectedLevel_1 = { currentView: { List6: "{{{backgroundColor: List6.backgroundColor,isVisible: List6.isVisible,itemSpacing: List6.itemSpacing,selectedItem: List6.selectedItem,triggeredItem: List6.triggeredItem,listData: List6.listData,pageNo: List6.pageNo,pageSize: List6.pageSize}}}", }, }; const metaNestedTextWidget = initialResult.metaWidgets[nestedTextWidgetId]; expect(metaNestedTextWidget.level_1).toEqual(expectedLevel_1); }); it("updates the bindings properties that use currentItem, currentView, currentIndex and level_", () => { const listWidgetName = "List6"; const nestedListWidgetId = "fs2d2lqjgd"; const cache = new Cache(); const generator = new MetaWidgetGenerator({ getWidgetCache: () => cache.getWidgetCache(nestedListWidgetId), setWidgetCache: (data) => cache.setWidgetCache(nestedListWidgetId, data), getWidgetReferenceCache: cache.getWidgetReferenceCache, setWidgetReferenceCache: cache.setWidgetReferenceCache, infiniteScroll: false, prefixMetaWidgetId: "fs2d2lqjgd", isListCloned: false, level: 2, onVirtualListScroll: jest.fn, primaryWidgetType: "LIST_WIDGET_V2", renderMode: RenderModes.CANVAS, }); const nestedListWidget = nestedListInput.templateWidgets[nestedListWidgetId]; const textWidgetId = "q8e2zhxsdb"; const textWidgetName = "Text5"; const expectedCurrentIndex = 0; const expectedCurrentItem = `{{${listWidgetName}.listData[${textWidgetName}.currentIndex]}}`; const expectedCurrentView = "{{{\n Text4: {isVisible: Text4.isVisible,text: Text4.text}\n }}}"; const expectedLevel_1 = { currentItem: "{{List1.listData[0]}}", currentIndex: 0, currentView: { Text1: "{{{isVisible: Text1.isVisible,text: Text1.text}}}", }, }; const initialResult = generator .withOptions({ ...DEFAULT_OPTIONS, currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListWidget.mainCanvasId, containerWidgetId: nestedListWidget.mainContainerId, levelData, pageSize: 3, widgetName: listWidgetName, }) .generate(); const textMetaWidget = initialResult.metaWidgets[textWidgetId]; expect(textMetaWidget.currentIndex).toEqual(expectedCurrentIndex); expect(textMetaWidget.currentItem).toEqual(expectedCurrentItem); expect(textMetaWidget.currentView).toEqual(expectedCurrentView); expect(textMetaWidget.level_1).toEqual(expectedLevel_1); }); it("adds data property to the container widget", () => { const { initialResult } = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, }, }); const expectedDataBinding = "{{\n {\n \n Image1: { image: Image1.image,isVisible: Image1.isVisible }\n ,\n Text1: { isVisible: Text1.isVisible,text: Text1.text }\n ,\n Text2: { isVisible: Text2.isVisible,text: Text2.text }\n ,\n List6: { backgroundColor: List6.backgroundColor,isVisible: List6.isVisible,itemSpacing: List6.itemSpacing,selectedItem: List6.selectedItem,selectedItemView: List6.selectedItemView,triggeredItemView: List6.triggeredItemView,items: List6.items,listData: List6.listData,pageNo: List6.pageNo,pageSize: List6.pageSize,selectedItemIndex: List6.selectedItemIndex,triggeredItemIndex: List6.triggeredItemIndex }\n \n }\n }}"; Object.values(initialResult.metaWidgets).forEach((widget) => { if (widget.type === "CONTAINER_WIDGET") { expect(widget.data).not.toBeUndefined(); if (widget.widgetId === simpleListInput.mainContainerId) { expect(widget.data).toEqual(expectedDataBinding); } } }); }); it("only the template meta widgets should have the actual widget name references in the bindings", () => { const { generator, initialResult, options } = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, }, }); options.pageSize = 3; options.data = [ { id: 0, name: "Green" }, { id: 1, name: "Blue" }, { id: 2, name: "Pink" }, { id: 3, name: "Black" }, { id: 4, name: "White" }, ]; options.primaryKeys = options.data.map((d) => (d.id as number).toString()); const { metaWidgets, removedMetaWidgetIds } = generator .withOptions(options) .generate(); const generatedMetaWidgets = { ...initialResult.metaWidgets, ...metaWidgets, }; const expectedDataBinding = "{{\n {\n \n Image1: { image: Image1.image,isVisible: Image1.isVisible }\n ,\n Text1: { isVisible: Text1.isVisible,text: Text1.text }\n ,\n Text2: { isVisible: Text2.isVisible,text: Text2.text }\n ,\n List6: { backgroundColor: List6.backgroundColor,isVisible: List6.isVisible,itemSpacing: List6.itemSpacing,selectedItem: List6.selectedItem,selectedItemView: List6.selectedItemView,triggeredItem: List6.triggeredItem,triggeredItemView: List6.triggeredItemView,listData: List6.listData,pageNo: List6.pageNo,pageSize: List6.pageSize,currentItemsView: List6.currentItemsView }\n \n }\n }}"; const count = Object.keys(metaWidgets).length; expect(count).toEqual(18); expect(removedMetaWidgetIds.length).toEqual(0); Object.values(generatedMetaWidgets).forEach((widget) => { if (widget.type === "CONTAINER_WIDGET") { expect(widget.data).not.toBeUndefined(); if (widget.widgetId === nestedListInput.mainContainerId) { expect(widget.data).toEqual(expectedDataBinding); } else { expect(widget.data).not.toEqual(expectedDataBinding); } } }); }); it("generates all meta widget and removes non first item meta widget when data re-shuffles in Edit mode", () => { const page1Data = [ { id: 1, name: "Blue" }, { id: 2, name: "Pink" }, ]; const page1PrimaryKeys = page1Data.map((d) => d.id.toString()); const page2Data = [ { id: 3, name: "Red" }, { id: 4, name: "Blue" }, ]; const page2PrimaryKeys = page2Data.map((d) => d.id.toString()); /** * Here page1Data's first item got shuffled into 2nd item and * first item has id 5 */ const updatedPage1Data = [ { id: 5, name: "Green" }, { id: 1, name: "White" }, ]; const updatePage1PrimaryKeys = updatedPage1Data.map((d) => d.id.toString()); const { generator, initialResult, options } = init({ optionsProps: { data: page1Data, primaryKeys: page1PrimaryKeys, serverSidePagination: true, }, }); const count1 = Object.keys(initialResult.metaWidgets).length; expect(count1).toEqual(12); expect(initialResult.removedMetaWidgetIds.length).toEqual(0); const result2 = generator .withOptions({ ...options, data: page2Data, primaryKeys: page2PrimaryKeys, pageNo: 2, }) .generate(); const count2 = Object.keys(result2.metaWidgets).length; expect(count2).toEqual(12); expect(result2.removedMetaWidgetIds.length).toEqual(6); const result3 = generator .withOptions({ ...options, data: updatedPage1Data, primaryKeys: updatePage1PrimaryKeys, pageNo: 1, }) .generate(); const count3 = Object.keys(result3.metaWidgets).length; expect(count3).toEqual(12); expect(result3.removedMetaWidgetIds.length).toEqual(6); }); it("generates all meta widget and removes all meta widget when data re-shuffles in View mode", () => { const page1Data = [ { id: 1, name: "Blue" }, { id: 2, name: "Pink" }, ]; const page1PrimaryKeys = page1Data.map((d) => d.id.toString()); const page2Data = [ { id: 3, name: "Red" }, { id: 4, name: "Blue" }, ]; const page2PrimaryKeys = page2Data.map((d) => d.id.toString()); /** * Here page1Data's first item got shuffled into 2nd item and * first item has id 5 */ const updatedPage1Data = [ { id: 5, name: "Green" }, { id: 1, name: "White" }, ]; const updatePage1PrimaryKeys = updatedPage1Data.map((d) => d.id.toString()); const { generator, initialResult, options } = init({ constructorProps: { renderMode: RenderModes.PAGE, }, optionsProps: { data: page1Data, primaryKeys: page1PrimaryKeys, serverSidePagination: true, }, }); const count1 = Object.keys(initialResult.metaWidgets).length; expect(count1).toEqual(12); expect(initialResult.removedMetaWidgetIds.length).toEqual(0); const result2 = generator .withOptions({ ...options, data: page2Data, primaryKeys: page2PrimaryKeys, pageNo: 2, }) .generate(); const count2 = Object.keys(result2.metaWidgets).length; expect(count2).toEqual(12); expect(result2.removedMetaWidgetIds.length).toEqual(12); const result3 = generator .withOptions({ ...options, data: updatedPage1Data, primaryKeys: updatePage1PrimaryKeys, pageNo: 1, }) .generate(); const count3 = Object.keys(result3.metaWidgets).length; expect(count3).toEqual(12); expect(result3.removedMetaWidgetIds.length).toEqual(12); }); it("should not have any template widgets when renderMode is PAGE", () => { const { initialResult, options } = init({ constructorProps: { renderMode: RenderModes.PAGE }, }); const templateWidgetNames = Object.values(options.currTemplateWidgets).map( (w) => w.widgetName, ); const templateWidgetIds = Object.keys(options.currTemplateWidgets); Object.values(initialResult.metaWidgets).forEach( ({ widgetId, widgetName }) => { expect(templateWidgetIds).not.toContain(widgetId); expect(templateWidgetNames).not.toContain(widgetName); }, ); }); it("should have some template widgets and some meta widgets when renderMode is CANVAS", () => { const { initialResult } = init(); const options = DEFAULT_OPTIONS; const { currTemplateWidgets } = options; const { metaWidgets } = initialResult; const templateWidgetIds = Object.keys(currTemplateWidgets); const templateWidgetCount = Object.values(metaWidgets).reduce( (count, metaWidget) => { if (templateWidgetIds.includes(metaWidget.widgetId)) { count += 1; } return count; }, 0, ); const metaWidgetsCount = Object.keys(metaWidgets).length; const nonTemplateWidgetsCount = metaWidgetsCount - templateWidgetCount; expect(metaWidgetsCount).toEqual(12); expect(templateWidgetCount).toEqual(6); expect(nonTemplateWidgetsCount).toEqual(6); }); it("should add metaWidgetId to all the meta widgets", () => { const { initialResult } = init(); Object.values(initialResult.metaWidgets).forEach((metaWidget) => { expect(metaWidget.metaWidgetId).toBeDefined(); }); }); it("should match the metaWidgetId and meta widget's widgetId for row > 0", () => { const { initialResult } = init(); Object.values(initialResult.metaWidgets).forEach((metaWidget) => { if (metaWidget.currentIndex > 0) { expect(metaWidget.metaWidgetId).toEqual(metaWidget.widgetId); } }); }); it("should not match the widgetId and meta widget's widgetId for 0th row for every page", () => { const { generator, initialResult, options } = init(); const startIndex = (options.pageNo - 1) * options.pageSize; Object.values(initialResult.metaWidgets).forEach((metaWidget) => { if (metaWidget.currentIndex === startIndex) { expect(metaWidget.metaWidgetId).not.toEqual(metaWidget.widgetId); } else { expect(metaWidget.metaWidgetId).toEqual(metaWidget.widgetId); } }); options.pageNo = 2; const updatedStartIndex = (options.pageNo - 1) * options.pageSize; const result1 = generator.withOptions(options).generate(); Object.values(result1.metaWidgets).forEach((metaWidget) => { if (metaWidget.currentIndex === updatedStartIndex) { expect(metaWidget.metaWidgetId).not.toEqual(metaWidget.widgetId); } else { expect(metaWidget.metaWidgetId).toEqual(metaWidget.widgetId); } }); }); it("should regenerate all meta widgets on page toggle and remove only non template widgets", () => { const { generator, options } = init(); options.pageNo = 2; const result1 = generator.withOptions(options).generate(); const count1 = Object.keys(result1.metaWidgets).length; expect(count1).toEqual(12); expect(result1.removedMetaWidgetIds.length).toEqual(6); options.pageNo = 1; const result2 = generator.withOptions(options).generate(); const count2 = Object.keys(result2.metaWidgets).length; expect(count2).toEqual(12); expect(result2.removedMetaWidgetIds.length).toEqual(6); }); it("in edit mode it updates siblingMetaWidgets in the template widget", () => { const { generator, initialResult, options } = init(); options.pageNo = 2; const result1 = generator.withOptions(options).generate(); Object.values(result1.metaWidgets).forEach((metaWidget) => { if (metaWidget.widgetId === metaWidget.metaWidgetId) { expect(metaWidget.siblingMetaWidgets).toBe(undefined); } else { const prevPageMetaWidgetIds = Object.values(initialResult.metaWidgets) .filter( ({ referencedWidgetId }) => referencedWidgetId === metaWidget.widgetId, ) .map(({ metaWidgetId }) => metaWidgetId); expect(metaWidget.siblingMetaWidgets).toStrictEqual( prevPageMetaWidgetIds, ); } }); }); it("in view mode it updates siblingMetaWidgets in one of the candidate meta widget", () => { const { generator, initialResult, options } = init({ constructorProps: { renderMode: RenderModes.PAGE }, }); options.pageNo = 2; const result1 = generator.withOptions(options).generate(); // Object of templateWidget: candidateMetaWidget[] // If any one of the object properties has more than 1 candidateMetaWidget then siblingMetaWidgets is // being stored in more than on meta widget for a particular template widget. const candidateMetaWidgets: Record<string, string[]> = {}; Object.values(result1.metaWidgets).forEach((metaWidget) => { const { referencedWidgetId = "", siblingMetaWidgets, widgetId, } = metaWidget; if (siblingMetaWidgets) { if (!Array.isArray(candidateMetaWidgets[referencedWidgetId])) { candidateMetaWidgets[referencedWidgetId] = [widgetId]; } else { candidateMetaWidgets[referencedWidgetId].push(widgetId); } } }); Object.values(candidateMetaWidgets).forEach((candidateWidgets) => { const [candidateWidgetId] = candidateWidgets; const candidateWidget = result1.metaWidgets[candidateWidgetId]; const prevPageMetaWidgetIds = Object.values(initialResult.metaWidgets) .filter( ({ referencedWidgetId }) => referencedWidgetId === candidateWidget.referencedWidgetId, ) .map(({ metaWidgetId }) => metaWidgetId); expect(candidateWidgets.length).toBe(1); expect(candidateWidget.siblingMetaWidgets).toStrictEqual( prevPageMetaWidgetIds, ); }); }); it("captures all siblingMetaWidgets in the first inner list's widget in a nested list setup", () => { const cache = new Cache(); const nestedList1Page1 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 0, primaryKeys: ["1_1", "1_2", "1_3", "1_4"], }, constructorProps: { level: 2, isListCloned: false, }, passedCache: cache, }); const nestedList2Page1 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 1, primaryKeys: ["2_1", "2_2", "2_3", "2_4"], }, constructorProps: { level: 2, isListCloned: true, }, passedCache: cache, }); const page1MetaWidgets = { ...nestedList1Page1.initialResult.metaWidgets, ...nestedList2Page1.initialResult.metaWidgets, }; /** * We are considering nestedList2Page1 as nestedList2Page1 and nestedList1Page1 both together * form the page1's nested list and since we have to generate the inner lists as separate to mimic * the actual behaviour so the nestedList2Page1 would give the most updated siblings updates * */ const page1PropertyUpdates = nestedList2Page1.initialResult.propertyUpdates; expect(page1PropertyUpdates).not.toStrictEqual([]); page1PropertyUpdates.forEach(({ path, value: siblingsIds }) => { const [candidateWidgetId] = path.split("."); const candidateWidget = page1MetaWidgets[candidateWidgetId]; const expectedSiblings = Object.values(page1MetaWidgets) .filter( ({ referencedWidgetId }) => referencedWidgetId === candidateWidget.referencedWidgetId, ) .map(({ metaWidgetId }) => metaWidgetId); expect(siblingsIds).toStrictEqual(expectedSiblings); }); // Page 2 const nestedList1Page2 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 0, primaryKeys: ["3_1", "3_2", "3_3", "3_4"], }, constructorProps: { level: 2, isListCloned: false, }, passedCache: cache, }); const nestedList2Page2 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 1, primaryKeys: ["4_1", "4_2", "4_3", "4_4"], }, constructorProps: { level: 2, isListCloned: true, }, passedCache: cache, }); const page2MetaWidgets = { ...nestedList1Page2.initialResult.metaWidgets, ...nestedList2Page2.initialResult.metaWidgets, }; const allMetaWidgets = [ ...Object.values(page1MetaWidgets), ...Object.values(page2MetaWidgets), ]; const page2PropertyUpdates = nestedList2Page2.initialResult.propertyUpdates; expect(page2PropertyUpdates).not.toStrictEqual([]); expect(page2PropertyUpdates).not.toStrictEqual([]); page2PropertyUpdates.forEach(({ path, value: siblingsIds }) => { const [candidateWidgetId] = path.split("."); const candidateWidget = page2MetaWidgets[candidateWidgetId]; const expectedSiblings = allMetaWidgets .filter( ({ referencedWidgetId }) => referencedWidgetId === candidateWidget.referencedWidgetId, ) .map(({ metaWidgetId }) => metaWidgetId); expect(siblingsIds).toStrictEqual(expectedSiblings); }); }); }); describe("#getContainerParentCache", () => { it("always returns template item for fist item and non template for rest of the items in edit mode", () => { const cache = new Cache(); // Page 1 nested list widget const nestedList1Page1 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 0, primaryKeys: ["1_1", "1_2", "1_3", "1_4"], }, constructorProps: { level: 2, isListCloned: false, }, passedCache: cache, listWidgetId: "list1", }); const nestedList2Page1 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 1, primaryKeys: ["2_1", "2_2", "2_3", "2_4"], }, constructorProps: { level: 2, isListCloned: true, }, passedCache: cache, listWidgetId: "list2", }); const parentCacheList1Page1 = klona( nestedList1Page1.generator.getContainerParentCache(), ); const parentCacheList2Page1 = klona( nestedList2Page1.generator.getContainerParentCache(), ); // In page 2 we are trying to mimic if the items position got swapped i.e the 1st item is not 2nd and vice-versa const nestedList1Page2 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 0, primaryKeys: ["2_1", "2_2", "2_3", "2_4"], }, constructorProps: { level: 2, isListCloned: false, }, passedCache: cache, listWidgetId: "list2", }); const nestedList2Page2 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 1, primaryKeys: ["1_1", "1_2", "1_3", "1_4"], }, constructorProps: { level: 2, isListCloned: true, }, passedCache: cache, listWidgetId: "list1", }); const parentCacheList1Page2 = klona( nestedList1Page2.generator.getContainerParentCache(), ); const parentCacheList2Page2 = klona( nestedList2Page2.generator.getContainerParentCache(), ); // If the page 1 item 1 is equal to page 2 items 2 expect(parentCacheList1Page1?.originalMetaWidgetId).toEqual( parentCacheList2Page2?.originalMetaWidgetId, ); expect(parentCacheList1Page1?.originalMetaWidgetName).toEqual( parentCacheList2Page2?.originalMetaWidgetName, ); // If the page 1 item 2 is equal to page 2 items 1 expect(parentCacheList2Page1?.originalMetaWidgetId).toEqual( parentCacheList1Page2?.originalMetaWidgetId, ); expect(parentCacheList2Page1?.originalMetaWidgetName).toEqual( parentCacheList1Page2?.originalMetaWidgetName, ); // Page 1 item 1 is template item expect(parentCacheList1Page1?.metaWidgetId).toEqual( parentCacheList1Page1?.templateWidgetId, ); // Page 1 item 2 is not template item expect(parentCacheList2Page1?.metaWidgetId).not.toEqual( parentCacheList1Page1?.templateWidgetId, ); // Page 2 item 1 is template item expect(parentCacheList1Page2?.metaWidgetId).toEqual( parentCacheList1Page2?.templateWidgetId, ); // Page 2 item 2 is not template item expect(parentCacheList2Page2?.metaWidgetId).not.toEqual( parentCacheList1Page2?.templateWidgetId, ); }); it("always returns template item for fist item and non template for rest of the items in view mode", () => { const cache = new Cache(); // Page 1 nested list widget const nestedList1Page1 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 0, primaryKeys: ["1_1", "1_2", "1_3", "1_4"], }, constructorProps: { level: 2, isListCloned: false, renderMode: RenderModes.PAGE, }, passedCache: cache, listWidgetId: "list1", }); const nestedList2Page1 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 1, primaryKeys: ["2_1", "2_2", "2_3", "2_4"], }, constructorProps: { level: 2, isListCloned: true, renderMode: RenderModes.PAGE, }, passedCache: cache, listWidgetId: "list2", }); const parentCacheList1Page1 = klona( nestedList1Page1.generator.getContainerParentCache(), ); const parentCacheList2Page1 = klona( nestedList2Page1.generator.getContainerParentCache(), ); // In page 2 we are trying to mimic if the items position got swapped i.e the 1st item is not 2nd and vice-versa const nestedList1Page2 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 0, primaryKeys: ["2_1", "2_2", "2_3", "2_4"], }, constructorProps: { level: 2, isListCloned: false, renderMode: RenderModes.PAGE, }, passedCache: cache, listWidgetId: "list2", }); const nestedList2Page2 = init({ optionsProps: { currTemplateWidgets: nestedListInput.templateWidgets, containerParentId: nestedListInput.containerParentId, containerWidgetId: nestedListInput.mainContainerId, nestedViewIndex: 1, primaryKeys: ["1_1", "1_2", "1_3", "1_4"], }, constructorProps: { level: 2, isListCloned: true, renderMode: RenderModes.PAGE, }, passedCache: cache, listWidgetId: "list1", }); const parentCacheList1Page2 = klona( nestedList1Page2.generator.getContainerParentCache(), ); const parentCacheList2Page2 = klona( nestedList2Page2.generator.getContainerParentCache(), ); // If the page 1 item 1 is equal to page 2 items 2 expect(parentCacheList1Page1?.originalMetaWidgetId).toEqual( parentCacheList2Page2?.originalMetaWidgetId, ); expect(parentCacheList1Page1?.originalMetaWidgetName).toEqual( parentCacheList2Page2?.originalMetaWidgetName, ); // If the page 1 item 2 is equal to page 2 items 1 expect(parentCacheList2Page1?.originalMetaWidgetId).toEqual( parentCacheList1Page2?.originalMetaWidgetId, ); expect(parentCacheList2Page1?.originalMetaWidgetName).toEqual( parentCacheList1Page2?.originalMetaWidgetName, ); // Page 1 item 1 is non template item expect(parentCacheList1Page1?.metaWidgetId).not.toEqual( parentCacheList1Page1?.templateWidgetId, ); // Page 1 item 2 is not template item expect(parentCacheList2Page1?.metaWidgetId).not.toEqual( parentCacheList1Page1?.templateWidgetId, ); // Page 2 item 1 is not template item expect(parentCacheList1Page2?.metaWidgetId).not.toEqual( parentCacheList1Page2?.templateWidgetId, ); // Page 2 item 2 is not template item expect(parentCacheList2Page2?.metaWidgetId).not.toEqual( parentCacheList1Page2?.templateWidgetId, ); }); }); describe("#getStartIndex", () => { it("return valid starting index when Server Side Pagination is disabled", () => { const { generator, options } = init(); const result1 = generator.getStartIndex(); expect(result1).toEqual(0); options.pageNo = 3; const result2 = generator.withOptions(options).getStartIndex(); expect(result2).toEqual(4); }); it("return valid starting index when server side pagination is enabled", () => { const { generator, options } = init({ optionsProps: { serverSidePagination: true }, }); const result1 = generator.getStartIndex(); expect(result1).toEqual(0); options.pageNo = 3; const result2 = generator.withOptions(options).getStartIndex(); expect(result2).toEqual(4); }); }); describe("#getMetaContainers", () => { const { generator, options } = init(); let page1Containers = {}; it("returns meta containers", () => { const containers = generator.getMetaContainers(); page1Containers = containers; expect(containers.ids.length).toEqual(2); expect(containers.names.length).toEqual(2); }); it("returns new container on page change", () => { options.pageNo = 2; generator.withOptions(options).generate(); const containers = generator.getMetaContainers(); expect(containers.ids.length).toEqual(2); expect(containers.names.length).toEqual(2); expect(page1Containers).not.toEqual(containers); }); it("return previously generated containers when previous page is visited", () => { options.pageNo = 1; generator.withOptions(options).generate(); const containers = generator.getMetaContainers(); expect(containers.ids.length).toEqual(2); expect(containers.names.length).toEqual(2); expect(page1Containers).toEqual(containers); }); it("page 1 meta container should have the template widget name", () => { const containers = generator.getMetaContainers(); expect(containers.names[0]).toEqual("Container1"); expect(containers.names[1]).not.toEqual("Container1"); }); }); describe("#updateWidgetNameInDynamicBinding", () => { const { generator } = init(); const data = [ { binding: "Text1.isValid + Text1 + Text1.text", metaWidgetName: "List12_Text1_szn8dmq3qq_txbxl5n484", templateWidgetName: "Text1", expected: "List12_Text1_szn8dmq3qq_txbxl5n484.isValid + Text1 + List12_Text1_szn8dmq3qq_txbxl5n484.text", }, { binding: '{{Table1.processedTableData.map((currentRow, currentIndex) => ( currentRow["name"]))}}', metaWidgetName: "List1_Table1_szn8dmq3qq_l21enk0im8", templateWidgetName: "Table1", expected: '{{List1_Table1_szn8dmq3qq_l21enk0im8.processedTableData.map((currentRow, currentIndex) => ( currentRow["name"]))}}', }, ]; it("returns meta containers", () => { data.forEach( ({ binding, expected, metaWidgetName, templateWidgetName }) => { const updatedBinding = generator.updateWidgetNameInDynamicBinding( binding, metaWidgetName, templateWidgetName, ); expect(updatedBinding).toBe(expected); }, ); }); it("returns same binding value when it falsy", () => { ["", undefined, null, false].forEach((d: unknown) => { const updatedBinding = generator.updateWidgetNameInDynamicBinding( d as string, "test", "test", ); expect(updatedBinding).toBe(d); }); }); });
1,817
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ListWidgetV2/Queue.test.ts
import Queue from "./Queue"; enum TestType { A, B, C, D, } describe("#has", () => { it("returns true for item type present in queue", () => { const defaultQueueItems = [ { type: TestType.A }, { type: TestType.B, metadata: { foo: "bar " } }, ]; const queue = new Queue<TestType>(defaultQueueItems); const testCases = [TestType.A, TestType.B]; testCases.forEach((input) => { const output = queue.has(input); expect(output).toEqual(true); }); }); it("returns false for item type not present in queue", () => { const defaultQueueItems = [ { type: TestType.A }, { type: TestType.B, metadata: { foo: "bar " } }, ]; const queue = new Queue<TestType>(defaultQueueItems); const testCases = [TestType.C]; testCases.forEach((input) => { const output = queue.has(input); expect(output).toEqual(false); }); }); }); describe("#add", () => { it("adds object items to the queue", () => { const defaultQueueItems = [{ type: TestType.B, metadata: { foo: "bar " } }]; const queue = new Queue<TestType>(defaultQueueItems); const testCases = [ { type: TestType.A }, { type: TestType.C, metadata: {} }, ]; testCases.forEach((input) => { queue.add(input); expect(queue.has(input.type)).toEqual(true); }); }); it("adds item types only to the queue", () => { const defaultQueueItems = [{ type: TestType.B, metadata: { foo: "bar " } }]; const queue = new Queue<TestType>(defaultQueueItems); const testCases = [TestType.A, TestType.C]; testCases.forEach((input) => { queue.add(input); expect(queue.has(input)).toEqual(true); }); }); it("it throws error for non primitive types", () => { const defaultQueueItems = [{ type: TestType.B, metadata: { foo: "bar " } }]; const queue = new Queue<TestType>(defaultQueueItems); const testCases = [ null, undefined, { foo: "bar" }, ] as unknown as TestType[]; testCases.forEach((input) => { expect(() => queue.add(input)).toThrowError( `Queue.add - ${input} is not a primitive type (String, Number, Boolean)`, ); }); }); }); describe("#flush", () => { it("flushes the queue", () => { const defaultQueueItems = [{ type: TestType.B, metadata: { foo: "bar " } }]; const queue = new Queue<TestType>(defaultQueueItems); queue.flush(); expect(queue.has(defaultQueueItems[0].type)).toEqual(false); }); }); describe("#metadata", () => { it("returns metadata for default items", () => { const defaultQueueItems = [ { type: TestType.B, metadata: { foo: "bar " } }, { type: TestType.A }, ]; const queue = new Queue<TestType>(defaultQueueItems); const testCases = [ { input: TestType.A, expectedOutput: undefined }, { input: TestType.B, expectedOutput: defaultQueueItems[0].metadata }, ]; testCases.forEach(({ expectedOutput, input }) => { const output = queue.metadata(input); expect(output).toEqual(expectedOutput); }); }); it("returns metadata for default items added with #add method", () => { const defaultQueueItems = [{ type: TestType.B, metadata: { foo: "bar " } }]; const queue = new Queue<TestType>(defaultQueueItems); const newItems = [ { type: TestType.A }, { type: TestType.C, metadata: {} }, { type: TestType.D, metadata: { bar: " baz" } }, ]; const testCases = [...defaultQueueItems, ...newItems]; newItems.forEach(queue.add); testCases.forEach(({ metadata, type }) => { const output = queue.metadata(type); expect(output).toEqual(metadata); }); }); it("returns metadata for first encountered item if multiple found", () => { const defaultQueueItems = [{ type: TestType.B, metadata: { foo: "bar " } }]; const queue = new Queue<TestType>(defaultQueueItems); const newItems = [ { type: TestType.A }, { type: TestType.C, metadata: {} }, { type: TestType.C, metadata: { bar: " baz" } }, { type: TestType.B, metadata: { bar: " baz" } }, ]; const testCases = [ { input: TestType.A, expectedOutput: undefined }, { input: TestType.B, expectedOutput: defaultQueueItems[0].metadata }, { input: TestType.C, expectedOutput: newItems[1].metadata }, ]; newItems.forEach(queue.add); testCases.forEach(({ expectedOutput, input }) => { const output = queue.metadata(input); expect(output).toEqual(expectedOutput); }); }); });
1,828
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ListWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ListWidgetV2/widget/helper.test.ts
import type { FlattenedWidgetProps } from "WidgetProvider/constants"; import { getNumberOfChildListWidget, getNumberOfParentListWidget, } from "./helper"; const widgets = { "0": { widgetId: "0", type: undefined, parentId: undefined, children: ["139ik5upi0", "3oplcuqz12"], }, "3oplcuqz12": { widgetId: "3oplcuqz12", type: "LIST_WIDGET_V2", parentId: "0", children: ["69jgkaa2eu"], }, "69jgkaa2eu": { widgetId: "69jgkaa2eu", type: "CANVAS_WIDGET", parentId: "3oplcuqz12", children: ["a7ee6ec9iu"], }, a7ee6ec9iu: { widgetId: "a7ee6ec9iu", type: "CONTAINER_WIDGET", parentId: "69jgkaa2eu", children: ["hlb038yavj"], }, hlb038yavj: { widgetId: "hlb038yavj", type: "CANVAS_WIDGET", parentId: "a7ee6ec9iu", children: ["2s2tpbx8sm"], }, "2s2tpbx8sm": { widgetId: "2s2tpbx8sm", type: "LIST_WIDGET_V2", parentId: "hlb038yavj", children: ["cx176bx3re"], }, cx176bx3re: { widgetId: "cx176bx3re", type: "CANVAS_WIDGET", parentId: "2s2tpbx8sm", children: ["30yh4juxkl"], }, "30yh4juxkl": { widgetId: "30yh4juxkl", type: "CONTAINER_WIDGET", parentId: "cx176bx3re", children: ["m2rv93a8qt"], }, m2rv93a8qt: { widgetId: "m2rv93a8qt", type: "CANVAS_WIDGET", parentId: "30yh4juxkl", children: ["iz7xsw9rwx"], }, iz7xsw9rwx: { widgetId: "iz7xsw9rwx", type: "CONTAINER_WIDGET", parentId: "m2rv93a8qt", children: ["fmgpap28mr"], }, fmgpap28mr: { widgetId: "fmgpap28mr", type: "CANVAS_WIDGET", parentId: "iz7xsw9rwx", children: ["e3spa0gb41"], }, e3spa0gb41: { widgetId: "e3spa0gb41", type: "LIST_WIDGET_V2", parentId: "fmgpap28mr", children: ["yntrlyu08l"], }, yntrlyu08l: { widgetId: "yntrlyu08l", type: "CANVAS_WIDGET", parentId: "e3spa0gb41", children: ["7kpy7wguuv"], }, "7kpy7wguuv": { widgetId: "7kpy7wguuv", type: "CONTAINER_WIDGET", parentId: "yntrlyu08l", children: ["lra8uwgwtk"], }, lra8uwgwtk: { widgetId: "lra8uwgwtk", type: "CANVAS_WIDGET", parentId: "7kpy7wguuv", children: [], }, "139ik5upi0": { widgetId: "139ik5upi0", type: "LIST_WIDGET_V2", parentId: "0", children: ["5oqysabeac"], }, "5oqysabeac": { widgetId: "5oqysabeac", type: "CANVAS_WIDGET", parentId: "139ik5upi0", children: ["mkxlp9tm5r"], }, mkxlp9tm5r: { widgetId: "mkxlp9tm5r", type: "CONTAINER_WIDGET", parentId: "5oqysabeac", children: ["4rdfztkqm7"], }, "4rdfztkqm7": { widgetId: "4rdfztkqm7", type: "CANVAS_WIDGET", parentId: "mkxlp9tm5r", children: ["qjiycy9cia"], }, qjiycy9cia: { widgetId: "qjiycy9cia", type: "CONTAINER_WIDGET", parentId: "4rdfztkqm7", children: ["3917oy1o62"], }, "3917oy1o62": { widgetId: "3917oy1o62", type: "CANVAS_WIDGET", parentId: "qjiycy9cia", children: ["9fjkqovvbf"], }, "9fjkqovvbf": { widgetId: "9fjkqovvbf", type: "LIST_WIDGET_V2", parentId: "3917oy1o62", children: ["v3y02o9gde"], }, v3y02o9gde: { widgetId: "v3y02o9gde", type: "CANVAS_WIDGET", parentId: "9fjkqovvbf", children: ["okws6qxk8e"], }, okws6qxk8e: { widgetId: "okws6qxk8e", type: "CONTAINER_WIDGET", parentId: "v3y02o9gde", children: ["12fp6p9vkn"], }, "12fp6p9vkn": { widgetId: "12fp6p9vkn", type: "CANVAS_WIDGET", parentId: "okws6qxk8e", children: [], }, } as unknown as { [widgetId: string]: FlattenedWidgetProps }; describe("Helper functions", () => { it("1.getNumberOfChildListWidget", () => { expect(getNumberOfChildListWidget("139ik5upi0", widgets)).toEqual(2); }); it("2.getNumberOfParentListWidget", () => { expect(getNumberOfParentListWidget("lra8uwgwtk", widgets)).toEqual(3); }); });
1,832
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ListWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/ListWidgetV2/widget/propertyConfig.test.ts
import _ from "lodash"; import { defaultSelectedItemValidation, primaryColumnValidation, } from "./propertyConfig"; import type { ListWidgetProps } from "."; import type { ValidationResponse } from "constants/WidgetValidation"; describe(".primaryColumnValidation", () => { it("validates uniqueness of values with valid input", () => { const props = { listData: [ { id: 1, }, { id: 2, }, ], } as unknown as ListWidgetProps; const inputValue = [1, 2]; const expectedOutput = { isValid: true, parsed: inputValue, messages: [{ name: "", message: "" }], }; const output = primaryColumnValidation(inputValue, props, _); expect(output).toEqual(expectedOutput); }); it("invalidates when input keys are not unique", () => { const props = { listData: [ { id: 1, }, { id: 2, }, ], } as unknown as ListWidgetProps; const inputValue = [1, 2, 3]; const expectedOutput = { isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "This data identifier is evaluating to a duplicate value. Please use an identifier that evaluates to a unique value.", }, ], }; const output = primaryColumnValidation(inputValue, props, _); expect(output).toEqual(expectedOutput); }); it("returns empty with error when JS mode enabled and input value is non-array", () => { const props = { listData: [ { id: 1, }, { id: 2, }, ], dynamicPropertyPathList: [{ key: "primaryKeys" }], } as unknown as ListWidgetProps; const inputs = [true, "true", 0, 1, undefined, null]; inputs.forEach((input) => { const output = primaryColumnValidation(input, props, _); expect(output).toEqual({ isValid: false, parsed: undefined, messages: [ { name: "ValidationError", message: "Use currentItem or currentIndex to find a good data identifier. You can also combine two or more data attributes or columns.", }, ], }); }); }); it("returns empty with error when JS mode disabled and input value is non-array", () => { const props = { listData: [ { id: 1, }, { id: 2, }, ], } as unknown as ListWidgetProps; const inputs = [true, "true", 0, 1, undefined, null]; inputs.forEach((input) => { const output = primaryColumnValidation(input, props, _); expect(output).toEqual({ isValid: false, parsed: undefined, messages: [ { name: "ValidationError", message: "Select an option from the dropdown or toggle JS on to define a data identifier.", }, ], }); }); }); it("returns empty with error when JS mode enabled and input is empty", () => { const props = { listData: [ { id: 1, }, { id: 2, }, ], dynamicPropertyPathList: [{ key: "primaryKeys" }], } as unknown as ListWidgetProps; const input: unknown = []; const output = primaryColumnValidation(input, props, _); expect(output).toEqual({ isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "This data identifier evaluates to an empty array. Please use an identifier that evaluates to a valid value.", }, ], }); }); it("primary key that doesn't exist", () => { const props = { listData: [ { id: 1, }, { id: 2, }, ], dynamicPropertyPathList: [{ key: "primaryKeys" }], } as unknown as ListWidgetProps; const input: unknown = [null, null]; const output = primaryColumnValidation(input, props, _); expect(output).toEqual({ isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "This identifier isn't a data attribute. Use an existing data attribute as your data identifier.", }, ], }); }); it("primary key contain null value in array", () => { const props = { listData: [ { id: 1, }, { id: 12, }, { id: 14, }, { id: 11, }, ], dynamicPropertyPathList: [{ key: "primaryKeys" }], } as unknown as ListWidgetProps; const input: unknown = [1, null, undefined, 4]; const output = primaryColumnValidation(input, props, _); expect(output).toEqual({ isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "This data identifier evaluates to null or undefined. Please use an identifier that evaluates to a valid value.", }, ], }); }); it("validates uniqueness of values with their datatypes", () => { const props = { listData: [ { id: 1, }, { id: 2, }, { id: "2", }, ], } as unknown as ListWidgetProps; const inputValue = [1, 2, "2"]; const expectedOutput = { isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "This data identifier is evaluating to a duplicate value. Please use an identifier that evaluates to a unique value.", }, ], }; const output = primaryColumnValidation(inputValue, props, _); expect(output).toEqual(expectedOutput); }); it("no error when there's no list data or list data is empty", () => { const props = { listData: [], } as unknown as ListWidgetProps; const inputValue = [1, 2]; const expectedOutput = { isValid: true, parsed: inputValue, messages: [{ name: "", message: "" }], }; const output = primaryColumnValidation(inputValue, props, _); expect(output).toEqual(expectedOutput); }); }); describe(".defaultSelectedItemValidation", () => { it("accepts only number and string", () => { const validOutput = (parsed: unknown): ValidationResponse => ({ isValid: true, parsed: String(parsed), messages: [{ name: "", message: "" }], }); const inValidOutput = (parsed: unknown): ValidationResponse => ({ isValid: false, parsed, messages: [ { name: "TypeError", message: "This value must be string or number" }, ], }); const inputValues: [unknown, (value: unknown) => ValidationResponse][] = [ [1, validOutput], ["2", validOutput], [null, inValidOutput], [true, inValidOutput], [{}, inValidOutput], [[], inValidOutput], ]; for (const inputs of inputValues) { const value = inputs[0]; const expected = inputs[1]; const output = defaultSelectedItemValidation( value, {} as ListWidgetProps, _, ); expect(output).toEqual(expected(value)); } }); });
1,854
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/MenuButtonWidget/validations.test.ts
import _ from "lodash"; import { sourceDataArrayValidation } from "./validations"; describe("sourceDataArrayValidation", () => { it("Should test with valid values", () => { const mockSourceData = [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ]; const result = sourceDataArrayValidation( mockSourceData, undefined as any, _, ); const expected = { isValid: true, parsed: mockSourceData, messages: [{ name: "", message: "" }], }; expect(result).toStrictEqual(expected); }); it("Should test when sourceData has a length more than 10", () => { const mockSourceData = Array(11).fill((_: null, index: number) => { return { step: `#${index}`, task: `Task ${index}`, status: "--", action: "", }; }); const result = sourceDataArrayValidation( mockSourceData, undefined as any, _, ); const expected = { isValid: false, parsed: [], messages: [ { name: "RangeError", message: "Source data cannot have more than 10 items", }, ], }; expect(result).toStrictEqual(expected); }); it("Should test when sourceData is not an array", () => { const mockSourceData = { step: "#1", task: "Drop a table", status: "✅", action: "", }; const result = sourceDataArrayValidation( mockSourceData, undefined as any, _, ); const expected = { isValid: false, parsed: [], messages: [ { name: "TypeError", message: "This value does not evaluate to type Array", }, ], }; expect(result).toStrictEqual(expected); }); });
1,857
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/MenuButtonWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/MenuButtonWidget/widget/helper.test.ts
import { getKeysFromSourceDataForEventAutocomplete } from "./helper"; describe("getKeysFromSourceDataForEventAutocomplete", () => { it("Should test with valid values - array of objects", () => { const mockProps = [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ]; const result = getKeysFromSourceDataForEventAutocomplete(mockProps as any); const expected = { currentItem: { step: "", task: "", status: "", action: "", }, }; expect(result).toStrictEqual(expected); }); it("Should test with valid values - array of arrays of objects", () => { const mockProps = [ [ { gender: "male", name: "#1 Victor", email: "[email protected]", phone: "011-800-3906", id: "6125683T", nat: "IE", }, { gender: "male", name: "#1 Tobias", email: "[email protected]", phone: "84467012", id: "200247-8744", nat: "DK", }, { gender: "female", name: "#1 Jane", email: "[email protected]", phone: "(679) 516-8766", id: "098-73-7712", nat: "US", }, { gender: "female", name: "#1 Yaromira", email: "[email protected]", phone: "(099) B82-8594", id: null, nat: "UA", }, { gender: "male", name: "#1 Andre", email: "[email protected]", phone: "08-3115-5776", id: "876838842", nat: "AU", }, ], [ { gender: "male", name: "#2 Victor", email: "[email protected]", phone: "011-800-3906", id: "6125683T", nat: "IE", }, { gender: "male", name: "#2 Tobias", email: "[email protected]", phone: "84467012", id: "200247-8744", nat: "DK", }, { gender: "female", name: "#2 Jane", email: "[email protected]", phone: "(679) 516-8766", id: "098-73-7712", nat: "US", }, { gender: "female", name: "#2 Yaromira", email: "[email protected]", phone: "(099) B82-8594", id: null, nat: "UA", }, { gender: "male", name: "#2 Andre", email: "[email protected]", phone: "08-3115-5776", id: "876838842", nat: "AU", }, ], [ { gender: "male", name: "#3 Victor", email: "[email protected]", phone: "011-800-3906", id: "6125683T", nat: "IE", }, { gender: "male", name: "#3 Tobias", email: "[email protected]", phone: "84467012", id: "200247-8744", nat: "DK", }, { gender: "female", name: "#3 Jane", email: "[email protected]", phone: "(679) 516-8766", id: "098-73-7712", nat: "US", }, { gender: "female", name: "#3 Yaromira", email: "[email protected]", phone: "(099) B82-8594", id: null, nat: "UA", }, { gender: "male", name: "#3 Andre", email: "[email protected]", phone: "08-3115-5776", id: "876838842", nat: "AU", }, ], ]; const result = getKeysFromSourceDataForEventAutocomplete(mockProps as any); const expected = { currentItem: { gender: "", name: "", email: "", phone: "", id: "", nat: "", }, }; expect(result).toStrictEqual(expected); }); it("Should test with empty sourceData", () => { const mockProps = { __evaluation__: { evaluatedValues: { sourceData: [], }, }, }; const result = getKeysFromSourceDataForEventAutocomplete(mockProps as any); const expected = { currentItem: {} }; expect(result).toStrictEqual(expected); }); it("Should test without sourceData", () => { const mockProps = {}; const result = getKeysFromSourceDataForEventAutocomplete(mockProps as any); const expected = { currentItem: {} }; expect(result).toStrictEqual(expected); }); it("Should test with null values", () => { const mockProps = { __evaluation__: { evaluatedValues: { sourceData: [null, null, null], }, }, }; const result = getKeysFromSourceDataForEventAutocomplete(mockProps as any); const expected = { currentItem: {} }; expect(result).toStrictEqual(expected); }); });
1,875
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/MultiSelectTreeWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/MultiSelectTreeWidget/widget/derived.test.ts
import _ from "lodash"; import { flat } from "widgets/WidgetUtils"; import derivedProperty from "./derived"; const options = [ { label: "Blue", value: "BLUE", children: [ { label: "Dark Blue", value: "DARK BLUE", }, { label: "Light Blue", value: "LIGHT BLUE", }, ], }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, { label: "0", value: 0, }, { label: "1", value: 1, }, ]; const flattenedOptions = flat(options); describe("Derived property - TreeSelect Widget", () => { describe("#getIsValid", () => { it("return true when isRequired false and selectedOptionValue is empty string", () => { const isValid = derivedProperty.getIsValid( { isRequired: false, selectedOptionValues: [], }, null, _, ); expect(isValid).toBeTruthy(); }); it("return true when isRequired true and selectedOptionValue is not empty", () => { const isValid = derivedProperty.getIsValid( { selectedOptionValues: ["GREEN"], isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("return true when isRequired true and selectedOptionValue is a number", () => { const isValid = derivedProperty.getIsValid( { selectedOptionValues: [0], isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("return false when isRequired true and selectedOptionValue is empty", () => { const isValid = derivedProperty.getIsValid( { selectedOptionValues: [], isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); }); }); describe("#getSelectedOptionValues", () => { it("selectedOptionValue should have a value if defaultValue(String) is in option", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValues( { selectedOptionValueArr: ["GREEN"], flattenedOptions, }, null, _, ); expect(selectedOptionValue).toStrictEqual(["GREEN"]); }); it("selectedOptionValue should have a value if defaultValue(Number) is in option", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValues( { selectedOptionValueArr: [1], flattenedOptions, }, null, _, ); expect(selectedOptionValue).toStrictEqual([1]); }); it("selectedOptionValue should not have a value if defaultValue(string) is not in option ", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValues( { selectedOptionValueArr: ["YELLOW"], flattenedOptions, }, null, _, ); expect(selectedOptionValue).toStrictEqual([]); }); }); describe("#getSelectedOptionLabel", () => { it("selectedOptionLabel should have a value if defaultValue(String) is in option", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabels( { selectedOptionValues: ["GREEN"], flattenedOptions, }, null, _, ); expect(selectedOptionLabel).toStrictEqual(["Green"]); }); it("selectedOptionLabel should have a value if defaultValue(Number) is in option", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabels( { selectedOptionValues: [0], flattenedOptions, }, null, _, ); expect(selectedOptionLabel).toStrictEqual(["0"]); }); it("selectedOptionLabel should not have a value if defaultValue(string) is not in option", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabels( { selectedOptionValues: ["YELLOW"], flattenedOptions, }, null, _, ); expect(selectedOptionLabel).toStrictEqual([]); }); }); });
1,893
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/MultiSelectWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/MultiSelectWidgetV2/widget/propertyUtils.test.ts
import type { LoDashStatic } from "lodash"; import { set } from "lodash"; import _ from "lodash"; import { EVAL_VALUE_PATH } from "utils/DynamicBindingUtils"; import type { WidgetProps } from "widgets/BaseWidget"; import { labelKeyValidation, getLabelValueAdditionalAutocompleteData, getLabelValueKeyOptions, valueKeyValidation, } from "./propertyUtils"; import type { MultiSelectWidgetProps } from "."; import { defaultOptionValueValidation } from "./propertyUtils"; const props = { serverSideFiltering: false, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, { label: "2022", value: 2022 }, { label: "true", value: "true" }, { label: "null", value: "null" }, { label: "undefined", value: "undefined" }, { label: "1", value: "1" }, { label: "2", value: "2" }, ], }; const DEFAULT_ERROR_MESSAGE = { name: "TypeError", message: "value should match: Array<string | number> | Array<{label: string, value: string | number}>", }; const MISSING_FROM_OPTIONS = { name: "ValidationError", message: "Some or all default values are missing from options. Please update the values.", }; const MISSING_FROM_OPTIONS_AND_WRONG_FORMAT = { name: "ValidationError", message: "Default value is missing in options. Please use [{label : <string | num>, value : < string | num>}] format to show default for server side data", }; describe("defaultOptionValueValidation - ", () => { it("should get tested with empty string", () => { const input = ""; expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [], messages: [{ name: "", message: "" }], }); }); it("should get tested with array of strings", () => { const input = ["green", "red"]; expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: false, parsed: input, messages: [MISSING_FROM_OPTIONS], }); }); it("should get tested with array of strings and stringified options", () => { const input = ["green", "red"]; expect( defaultOptionValueValidation( input, { ...props, options: JSON.stringify(props.options) as unknown, } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: false, parsed: input, messages: [MISSING_FROM_OPTIONS], }); }); it("should get tested with a number", () => { const input = 2022; expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [input], messages: [{ name: "", message: "" }], }); }); it("should get tested with a string", () => { const inputs = [2022, "true", "null", "undefined"]; inputs.forEach((input) => { expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [input], messages: [{ name: "", message: "" }], }); }); }); it("should get tested with array json string", () => { const input = `["GREEN", "RED"]`; expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: ["GREEN", "RED"], messages: [{ name: "", message: "" }], }); }); it("should get tested with array of object json string", () => { const input = `[ { "label": "green", "value": "GREEN" }, { "label": "red", "value": "RED" } ]`; expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [ { label: "green", value: "GREEN", }, { label: "red", value: "RED", }, ], messages: [{ name: "", message: "" }], }); }); it("should get tested with comma separated strings", () => { const input = "GREEN, RED"; const input2 = "1, 2"; expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: ["GREEN", "RED"], messages: [{ name: "", message: "" }], }); expect( defaultOptionValueValidation( input2, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: ["1", "2"], messages: [{ name: "", message: "" }], }); }); it("should get tested with string and ServerSide filtering on", () => { const input = "YELLOW"; expect( defaultOptionValueValidation( input, { ...props, serverSideFiltering: true } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: false, parsed: ["YELLOW"], messages: [MISSING_FROM_OPTIONS_AND_WRONG_FORMAT], }); }); it("should get tested with simple string", () => { const input = `{"green"`; expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [`{"green"`], messages: [MISSING_FROM_OPTIONS], }); }); it("should get tested with array of label, value and serverside filtering off", () => { const input = [ { label: "green", value: "green", }, { label: "red", value: "red", }, ]; expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [ { label: "green", value: "green", }, { label: "red", value: "red", }, ], messages: [MISSING_FROM_OPTIONS], }); }); it("should get tested with array of invalid values", () => { const testValues = [ [ undefined, { isValid: false, parsed: [], messages: [DEFAULT_ERROR_MESSAGE], }, ], [ null, { isValid: false, parsed: [], messages: [DEFAULT_ERROR_MESSAGE], }, ], [ true, { isValid: false, parsed: [], messages: [DEFAULT_ERROR_MESSAGE], }, ], [ {}, { isValid: false, parsed: [], messages: [DEFAULT_ERROR_MESSAGE], }, ], [ [undefined], { isValid: false, parsed: [], messages: [DEFAULT_ERROR_MESSAGE], }, ], [ [true], { isValid: false, parsed: [], messages: [DEFAULT_ERROR_MESSAGE], }, ], [ ["green", "green"], { isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "values must be unique. Duplicate values found", }, ], }, ], [ [ { label: "green", value: "green", }, { label: "green", value: "green", }, ], { isValid: false, parsed: [], messages: [ { name: "ValidationError", message: "path:value must be unique. Duplicate values found", }, ], }, ], [ [ { label: "green", }, { label: "green", }, ], { isValid: false, parsed: [], messages: [DEFAULT_ERROR_MESSAGE], }, ], ]; testValues.forEach(([input, expected]) => { expect( defaultOptionValueValidation( input, { ...props } as MultiSelectWidgetProps, _, ), ).toEqual(expected); }); }); }); describe("labelKeyValidation", () => { test("should test that empty values return error", () => { ["", undefined, null].forEach((d) => { expect( labelKeyValidation(d, {} as MultiSelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: `value does not evaluate to type: string | Array<string>`, }, ], }); }); }); test("should test that string values validates", () => { expect( labelKeyValidation( "test", {} as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "test", isValid: true, messages: [], }); }); test("should test that array of string value validates", () => { expect( labelKeyValidation( ["blue", "green", "yellow"], {} as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: ["blue", "green", "yellow"], isValid: true, messages: [], }); }); test("should test that all other values return error", () => { //invalid array entry [ ["blue", 1, "yellow"], ["blue", {}, "yellow"], ["blue", true, "yellow"], ["blue", [], "yellow"], ["blue", undefined, "yellow"], ["blue", null, "yellow"], ].forEach((d) => { expect( labelKeyValidation(d, {} as MultiSelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: [], isValid: false, messages: [ { name: "ValidationError", message: `Invalid entry at index: 1. This value does not evaluate to type: string`, }, ], }); }); // boolean expect( labelKeyValidation(true, {} as MultiSelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string>", }, ], }); // number expect( labelKeyValidation(1, {} as MultiSelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string>", }, ], }); // object expect( labelKeyValidation({}, {} as MultiSelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string>", }, ], }); }); }); describe("valueKeyValidation", () => { test("should test that empty values return error", () => { ["", undefined, null].forEach((d) => { expect( valueKeyValidation( d, { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: `value does not evaluate to type: string | Array<string| number | boolean>`, }, ], }); }); }); test("should test that string values validates", () => { expect( valueKeyValidation( "test", { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "test", isValid: true, messages: [], }); }); test("should test that array of string | number | boolean value validates", () => { [ ["blue", 1, "yellow"], ["blue", true, "yellow"], [1, 2, 3], ].forEach((d) => { expect( valueKeyValidation( d, { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: d, isValid: true, messages: [], }); }); }); test("should test that all other values return error", () => { //invalid array entry [ ["blue", {}, "yellow"], ["blue", [], "yellow"], ["blue", undefined, "yellow"], ["blue", null, "yellow"], ].forEach((d) => { expect( valueKeyValidation( d, { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: [], isValid: false, messages: [ { name: "ValidationError", message: `Invalid entry at index: 1. This value does not evaluate to type: string | number | boolean`, }, ], }); }); expect( valueKeyValidation( ["blue", "blue", "yellow"], { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: ["blue", "blue", "yellow"], isValid: false, messages: [ { name: "ValidationError", message: `Duplicate values found, value must be unique`, }, ], }); expect( valueKeyValidation( "yellow", { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "yellow", isValid: false, messages: [ { name: "ValidationError", message: `value key should be present in the source data`, }, ], }); // boolean expect( valueKeyValidation( true, { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string | number | boolean>", }, ], }); // number expect( valueKeyValidation( 1, { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string | number | boolean>", }, ], }); // object expect( valueKeyValidation( {}, { sourceData: [{ test: 1 }, { test: 2 }], } as any as MultiSelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string | number | boolean>", }, ], }); }); }); describe("getLabelValueKeyOptions", () => { test("should test that keys are properly generated for valid values", () => { [ { input: JSON.stringify([ { "1": "", "2": "", }, { "1": "", "2": "", }, ]), output: [ { label: "1", value: "1", }, { label: "2", value: "2", }, ], }, { input: [ { "1": "", "2": "", }, { "1": "", "2": "", }, ], output: [ { label: "1", value: "1", }, { label: "2", value: "2", }, ], }, { input: [ { "1": "", "2": "", }, { "3": "", "4": "", }, { "1": "", "2": "", "3": "", "4": "", }, "test", 1, true, {}, undefined, null, ], output: [ { label: "1", value: "1", }, { label: "2", value: "2", }, { label: "3", value: "3", }, { label: "4", value: "4", }, ], }, ].forEach((d) => { const widget = {}; set(widget, `${EVAL_VALUE_PATH}.sourceData`, d.input); expect(getLabelValueKeyOptions(widget as WidgetProps)).toEqual(d.output); }); }); test("should test that empty array is generated for invalid values", () => { [[], "", null, undefined, {}, true, 1].forEach((d) => { const widget = {}; set(widget, `${EVAL_VALUE_PATH}.sourceData`, d); expect(getLabelValueKeyOptions(widget as WidgetProps)).toEqual([]); }); }); }); describe("getLabelValueAdditionalAutocompleteData", () => { test("should test autocompletObject is generated for valid value", () => { [ { input: JSON.stringify([ { "1": "", "2": "", }, { "1": "", "2": "", }, ]), output: { item: { 1: "", 2: "", }, }, }, { input: [ { "1": "", "2": "", }, { "1": "", "2": "", }, ], output: { item: { 1: "", 2: "", }, }, }, { input: [ { "1": "", "2": "", }, { "3": "", "4": "", "5": "", }, { "1": "", "2": "", "3": "", "4": "", }, "test", 1, true, {}, undefined, null, ], output: { item: { 1: "", 2: "", 3: "", 4: "", 5: "", }, }, }, ].forEach((d) => { const widget = {}; set(widget, `${EVAL_VALUE_PATH}.sourceData`, d.input); expect( getLabelValueAdditionalAutocompleteData(widget as WidgetProps), ).toEqual(d.output); }); }); test("should test that empty item is generated for invalid values", () => { [[], "", null, undefined, {}, true, 1].forEach((d) => { const widget = {}; set(widget, `${EVAL_VALUE_PATH}.sourceData`, d); expect( getLabelValueAdditionalAutocompleteData(widget as WidgetProps), ).toEqual({ item: {}, }); }); }); });
1,913
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/PhoneInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/PhoneInputWidget/component/utilities.test.ts
import { countryToFlag } from "./utilities"; describe("Utilities - ", () => { it("should test countryToFlag", () => { [ ["+91", "🇮🇳"], ["+1", "🇺🇸"], ["", ""], ].forEach((d) => { expect(countryToFlag(d[0])).toBe(d[1]); }); }); });
1,916
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/PhoneInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/PhoneInputWidget/widget/derived.test.ts
import derivedProperty from "./derived"; describe("Derived property - ", () => { describe("isValid property", () => { it("should test isRequired", () => { let isValid = derivedProperty.isValid({ text: undefined, isRequired: false, }); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid({ text: undefined, isRequired: true, }); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid({ value: "0000000000", text: "0000000000", isRequired: true, }); expect(isValid).toBeTruthy(); }); it("should test validation", () => { let isValid = derivedProperty.isValid({ value: "0000000000", text: "0000000000", validation: false, }); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid({ value: "0000000000", text: "0000000000", validation: true, }); expect(isValid).toBeTruthy(); }); it("should test regex validation", () => { let isValid = derivedProperty.isValid({ value: "0000000000", text: "0000000000", regex: "^0000000000$", }); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid({ value: "0000000001", text: "0000000001", regex: "^0000000000$", }); expect(isValid).toBeFalsy(); }); }); });
1,917
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/PhoneInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/PhoneInputWidget/widget/index.test.tsx
import type { PhoneInputWidgetProps } from "./index"; import { defaultValueValidation } from "./index"; import _ from "lodash"; describe("defaultValueValidation", () => { let result: any; it("should validate defaulttext", () => { result = defaultValueValidation( "0000000000", {} as PhoneInputWidgetProps, _, ); expect(result).toEqual({ isValid: true, parsed: "0000000000", messages: [{ name: "", message: "" }], }); }); it("should validate defaulttext with object value", () => { const value = {}; result = defaultValueValidation(value, {} as PhoneInputWidgetProps, _); expect(result).toEqual({ isValid: false, parsed: JSON.stringify(value, null, 2), messages: [ { name: "TypeError", message: "This value must be string", }, ], }); }); });
1,940
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/RadioGroupWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/RadioGroupWidget/widget/propertyPaneConfig.test.ts
import _ from "lodash"; import RadioGroupWidget from "./index"; describe("unit test case for property config pane", () => { it("case: check the value returned by defaultOptionValue", () => { const dataSection: any = RadioGroupWidget.getPropertyPaneContentConfig().filter( (section: any) => section.sectionName === "Data", ); const dsv = dataSection[0].children.filter( (child: any) => child.propertyName === "defaultOptionValue", )[0]; const dsvValidationFunc = dsv.validation.params.fn; expect(dsvValidationFunc(1, {}, _)).toEqual({ isValid: true, parsed: 1 }); expect(dsvValidationFunc("1", {}, _)).toEqual({ isValid: true, parsed: "1", }); }); });
1,960
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/SelectWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/SelectWidget/component/SelectButton.test.tsx
import React from "react"; import { IconWrapper } from "@design-system/widgets-old"; import { fireEvent, render } from "@testing-library/react"; import type { SelectButtonProps } from "./SelectButton"; import SelectButton from "./SelectButton"; // It is necessary to make a mock of the Icon component as the error falls due to React.lazy in importIconImpl jest.mock("@design-system/widgets-old", () => { const originalModule = jest.requireActual("@design-system/widgets-old"); return { __esModule: true, ...originalModule, Icon: (props: any) => { return <IconWrapper {...props} />; }, }; }); const defaultProps: SelectButtonProps = { disabled: false, displayText: "0", handleCancelClick: jest.fn(), spanRef: null, togglePopoverVisibility: jest.fn(), tooltipText: "", value: "0", }; const renderComponent = (props: SelectButtonProps = defaultProps) => { return render(<SelectButton {...props} />); }; describe("SelectButton", () => { it("should not fire click event when disabled", () => { const { getByTestId, getByText } = renderComponent({ ...defaultProps, disabled: true, }); fireEvent.click(getByTestId("selectbutton.btn.main")); expect(defaultProps.togglePopoverVisibility).not.toBeCalled(); expect(getByText("0")).toBeTruthy(); }); it("should render correctly", async () => { const { getByText } = renderComponent(); expect(getByText("0")).toBeTruthy(); }); it("should trigger handleCancelClick method on cancel click", () => { const { getByTestId } = renderComponent(); fireEvent.click(getByTestId("selectbutton.btn.cancel")); expect(defaultProps.handleCancelClick).toBeCalled(); }); it("should toggle popover visibility method on button click", () => { const { getByTestId } = renderComponent(); fireEvent.click(getByTestId("selectbutton.btn.main")); expect(defaultProps.togglePopoverVisibility).toBeCalled(); }); });
1,965
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/SelectWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/SelectWidget/widget/derived.test.ts
import _ from "lodash"; import derivedProperty from "./derived"; describe("Derived property - Select Widget", () => { describe("#getIsValid", () => { it("return true when isRequired false and selectedOptionValue is empty string", () => { const isValid = derivedProperty.getIsValid( { isRequired: false, selectedOptionValue: "", }, null, _, ); expect(isValid).toBeTruthy(); }); it("return true when isRequired true and selectedOptionValue is not empty", () => { const isValid = derivedProperty.getIsValid( { selectedOptionValue: "GREEN", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("return false when isRequired true and selectedOptionValue is empty", () => { const isValid = derivedProperty.getIsValid( { selectedOptionValue: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); }); }); describe("#getSelectedOptionValue", () => { it("selectedOptionValue should have a value if defaultValue(String) is in option", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { serverSideFiltering: false, value: "GREEN", options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionValue).toBe("GREEN"); }); it("selectedOptionValue should have a value if defaultValue(Object) is in option", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { serverSideFiltering: false, value: { label: "Green", value: "GREEN" }, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionValue).toBe("GREEN"); }); it("selectedOptionValue should not have a value if defaultValue(Object) is not in option and serverSideFiltering is false", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { serverSideFiltering: false, value: { label: "Yellow", value: "YELLOW" }, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionValue).toBe(""); }); it("selectedOptionValue should not have a value if defaultValue(string) is not in option and serverSideFiltering is false", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { serverSideFiltering: false, value: "YELLOW", options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionValue).toBe(""); }); it("selectedOptionValue should have a value if defaultValue(object) is not in option and serverSideFiltering is true", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { serverSideFiltering: true, value: { label: "Yellow", value: "YELLOW" }, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionValue).toBe("YELLOW"); }); it("selectedOptionValue should have a value if defaultValue(string) is not in option and serverSideFiltering is true", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { serverSideFiltering: true, value: "YELLOW", isDirty: false, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionValue).toBe(""); }); }); describe("#getSelectedOptionLabel", () => { it("selectedOptionLabel should have a value if defaultValue(String) is in option", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: "GREEN", serverSideFiltering: false, label: "GREEN", options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionLabel).toBe("Green"); }); it("selectedOptionLabel should have a value if defaultValue(Object) is in option", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: "GREEN", serverSideFiltering: false, label: { label: "Green", value: "GREEN" }, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionLabel).toBe("Green"); }); it("selectedOptionLabel should have it's value from the options and not from defaultValue(Object)", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: "GREEN", serverSideFiltering: false, label: { label: "Greenish", value: "GREEN" }, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionLabel).toBe("Green"); }); it("selectedOptionLabel should not have a value if defaultValue(Object) is not in option and serverSideFiltering is false", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: "", serverSideFiltering: false, label: { label: "Yellow", value: "YELLOW" }, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionLabel).toBe(""); }); it("selectedOptionLabel should not have a value if defaultValue(string) is not in option and serverSideFiltering is false", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: "", serverSideFiltering: false, label: "YELLOW", options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionLabel).toBe(""); }); it("selectedOptionLabel should have a value if defaultValue(object) is not in option and serverSideFiltering is true", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { serverSideFiltering: true, label: { label: "Yellow", value: "YELLOW" }, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionLabel).toBe("Yellow"); }); it("selectedOptionLabel should have it's value from the options and not from defaultValue(Object) and serverSideFiltering is true", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: "GREEN", serverSideFiltering: true, label: { label: "Greenish", value: "GREEN" }, options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionLabel).toBe("Green"); }); it("selectedOptionLabel should have it's value if defaultValue(string) and serverSideFiltering is true", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { serverSideFiltering: true, selectedOptionValue: "", label: "YELLOW", options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, { label: "Red", value: "RED" }, ], }, null, _, ); expect(selectedOptionLabel).toBe(""); }); }); });
1,968
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/SelectWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/SelectWidget/widget/propertyUtils.test.ts
import type { LoDashStatic } from "lodash"; import { set } from "lodash"; import _ from "lodash"; import { EVAL_VALUE_PATH } from "utils/DynamicBindingUtils"; import type { WidgetProps } from "widgets/BaseWidget"; import type { SelectWidgetProps } from "."; import { defaultOptionValueValidation, labelKeyValidation, getLabelValueAdditionalAutocompleteData, getLabelValueKeyOptions, valueKeyValidation, } from "./propertyUtils"; describe("defaultOptionValueValidation - ", () => { it("should get tested with simple string", () => { const input = ""; expect( defaultOptionValueValidation(input, {} as SelectWidgetProps, _), ).toEqual({ isValid: true, parsed: "", messages: [{ name: "", message: "" }], }); }); it("should get tested with number", () => { const testValues = [ [ "1", { isValid: true, parsed: "1", messages: [{ name: "", message: "" }], }, ], [ 1, { isValid: true, parsed: 1, messages: [{ name: "", message: "" }], }, ], ]; testValues.forEach(([input, expected]) => { expect( defaultOptionValueValidation( input, { options: [ { label: "Blue", value: "1" }, { label: "Green", value: 1 }, ], serverSideFiltering: false, } as SelectWidgetProps, _, ), ).toEqual(expected); }); }); it("should get tested with simple string", () => { const input = "green"; expect( defaultOptionValueValidation( input, { options: [{ label: "Green", value: "green" }], serverSideFiltering: false, } as SelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: "green", messages: [{ name: "", message: "" }], }); }); it("should get tested with simple string with stringified options", () => { const input = "green"; expect( defaultOptionValueValidation( input, { options: JSON.stringify([ { label: "Green", value: "green" }, ]) as unknown, serverSideFiltering: false, } as SelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: "green", messages: [{ name: "", message: "" }], }); }); it("should get tested with plain object", () => { const input = { label: "green", value: "green", }; expect( defaultOptionValueValidation( input, { options: [{ label: "Green", value: "green" }], serverSideFiltering: false, } as SelectWidgetProps, _, ), ).toEqual({ isValid: true, parsed: { label: "green", value: "green", }, messages: [{ name: "", message: "" }], }); }); it("should get tested with valid strings", () => { const testValues = [ [ "undefined", { isValid: true, parsed: "undefined", messages: [{ name: "", message: "" }], }, ], [ "null", { isValid: true, parsed: "null", messages: [{ name: "", message: "" }], }, ], [ "true", { isValid: true, parsed: "true", messages: [{ name: "", message: "" }], }, ], ]; testValues.forEach(([input, expected]) => { expect( defaultOptionValueValidation( input, { options: [ { label: "null", value: "null" }, { label: "undefined", value: "undefined" }, { label: "true", value: "true" }, ], serverSideFiltering: false, } as SelectWidgetProps, _, ), ).toEqual(expected); }); }); it("should get tested with invalid values", () => { const testValues = [ [ undefined, { isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: `value does not evaluate to type: string | number | { "label": "label1", "value": "value1" }`, }, ], }, ], [ null, { isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: `value does not evaluate to type: string | number | { "label": "label1", "value": "value1" }`, }, ], }, ], [ [], { isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: `value does not evaluate to type: string | number | { "label": "label1", "value": "value1" }`, }, ], }, ], [ true, { isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: `value does not evaluate to type: string | number | { "label": "label1", "value": "value1" }`, }, ], }, ], [ { label: "green", }, { isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: `value does not evaluate to type: string | number | { "label": "label1", "value": "value1" }`, }, ], }, ], ]; testValues.forEach(([input, expected]) => { expect( defaultOptionValueValidation( input, { options: [ { label: "null", value: "null" }, { label: "undefined", value: "undefined" }, { label: "true", value: "true" }, ], serverSideFiltering: false, } as SelectWidgetProps, _, ), ).toEqual(expected); }); }); it("Should get tested with options when serverSideFiltering is false ", () => { const input = "YELLOW"; expect( defaultOptionValueValidation( input, { options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, ], serverSideFiltering: false, } as SelectWidgetProps, _, ), ).toEqual({ isValid: false, parsed: "YELLOW", messages: [ { name: "ValidationError", message: "Default value is missing in options. Please update the value.", }, ], }); }); it("Should get tested with options when serverSideFiltering is true ", () => { const input = "YELLOW"; expect( defaultOptionValueValidation( input, { options: [ { label: "Blue", value: "BLUE" }, { label: "Green", value: "GREEN" }, ], serverSideFiltering: true, } as SelectWidgetProps, _, ), ).toEqual({ isValid: false, parsed: "YELLOW", messages: [ { name: "ValidationError", message: "Default value is missing in options. Please use {label : <string | num>, value : < string | num>} format to show default for server side data.", }, ], }); }); }); describe("labelKeyValidation", () => { test("should test that empty values return error", () => { ["", undefined, null].forEach((d) => { expect( labelKeyValidation(d, {} as SelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: `value does not evaluate to type: string | Array<string>`, }, ], }); }); }); test("should test that string values validates", () => { expect( labelKeyValidation("test", {} as SelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "test", isValid: true, messages: [], }); }); test("should test that array of string value validates", () => { expect( labelKeyValidation( ["blue", "green", "yellow"], {} as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: ["blue", "green", "yellow"], isValid: true, messages: [], }); }); test("should test that all other values return error", () => { //invalid array entry [ ["blue", 1, "yellow"], ["blue", {}, "yellow"], ["blue", true, "yellow"], ["blue", [], "yellow"], ["blue", undefined, "yellow"], ["blue", null, "yellow"], ].forEach((d) => { expect( labelKeyValidation(d, {} as SelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: [], isValid: false, messages: [ { name: "ValidationError", message: `Invalid entry at index: 1. This value does not evaluate to type: string`, }, ], }); }); // boolean expect( labelKeyValidation(true, {} as SelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string>", }, ], }); // number expect( labelKeyValidation(1, {} as SelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string>", }, ], }); // object expect( labelKeyValidation({}, {} as SelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string>", }, ], }); }); }); describe("valueKeyValidation", () => { test("should test that empty values return error", () => { ["", undefined, null].forEach((d) => { expect( valueKeyValidation(d, {} as SelectWidgetProps, _ as LoDashStatic), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: `value does not evaluate to type: string | Array<string| number | boolean>`, }, ], }); }); }); test("should test that string values validates", () => { expect( valueKeyValidation( "test", { sourceData: [{ test: 1 }, { test: 2 }] } as any as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "test", isValid: true, messages: [], }); }); test("should test that array of string | number | boolean value validates", () => { [ ["blue", 1, "yellow"], ["blue", true, "yellow"], [1, 2, 3], ].forEach((d) => { expect( valueKeyValidation( d, { sourceData: [{ test: 1 }, { test: 2 }], } as any as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: d, isValid: true, messages: [], }); }); }); test("should test that all other values return error", () => { //invalid array entry [ ["blue", {}, "yellow"], ["blue", [], "yellow"], ["blue", undefined, "yellow"], ["blue", null, "yellow"], ].forEach((d) => { expect( valueKeyValidation( d, { sourceData: [{ test: 1 }, { test: 2 }], } as any as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: [], isValid: false, messages: [ { name: "ValidationError", message: `Invalid entry at index: 1. This value does not evaluate to type: string | number | boolean`, }, ], }); }); //duplicate array entry expect( valueKeyValidation( ["blue", "blue", "yellow"], { sourceData: [{ test: 1 }, { test: 2 }], } as any as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: ["blue", "blue", "yellow"], isValid: false, messages: [ { name: "ValidationError", message: `Duplicate values found, value must be unique`, }, ], }); expect( valueKeyValidation( "yellow", { sourceData: [{ test: 1 }, { test: 2 }], } as any as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "yellow", isValid: false, messages: [ { name: "ValidationError", message: `value key should be present in the source data`, }, ], }); // boolean expect( valueKeyValidation( true, { sourceData: [{ test: 1 }, { test: 2 }] } as any as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string | number | boolean>", }, ], }); // number expect( valueKeyValidation( 1, { sourceData: [{ test: 1 }, { test: 2 }] } as any as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string | number | boolean>", }, ], }); // object expect( valueKeyValidation( {}, { sourceData: [{ test: 1 }, { test: 2 }] } as any as SelectWidgetProps, _ as LoDashStatic, ), ).toEqual({ parsed: "", isValid: false, messages: [ { name: "ValidationError", message: "value does not evaluate to type: string | Array<string | number | boolean>", }, ], }); }); }); describe("getLabelValueKeyOptions", () => { test("should test that keys are properly generated for valid values", () => { [ { input: JSON.stringify([ { "1": "", "2": "", }, { "1": "", "2": "", }, ]), output: [ { label: "1", value: "1", }, { label: "2", value: "2", }, ], }, { input: [ { "1": "", "2": "", }, { "1": "", "2": "", }, ], output: [ { label: "1", value: "1", }, { label: "2", value: "2", }, ], }, { input: [ { "1": "", "2": "", }, { "3": "", "4": "", }, { "1": "", "2": "", "3": "", "4": "", }, "test", 1, true, {}, undefined, null, ], output: [ { label: "1", value: "1", }, { label: "2", value: "2", }, { label: "3", value: "3", }, { label: "4", value: "4", }, ], }, ].forEach((d) => { const widget = {}; set(widget, `${EVAL_VALUE_PATH}.sourceData`, d.input); expect(getLabelValueKeyOptions(widget as WidgetProps)).toEqual(d.output); }); }); test("should test that empty array is generated for invalid values", () => { [[], "", null, undefined, {}, true, 1].forEach((d) => { const widget = {}; set(widget, `${EVAL_VALUE_PATH}.sourceData`, d); expect(getLabelValueKeyOptions(widget as WidgetProps)).toEqual([]); }); }); }); describe("getLabelValueAdditionalAutocompleteData", () => { test("should test autocompletObject is generated for valid value", () => { [ { input: JSON.stringify([ { "1": "", "2": "", }, { "1": "", "2": "", }, ]), output: { item: { 1: "", 2: "", }, }, }, { input: [ { "1": "", "2": "", }, { "1": "", "2": "", }, ], output: { item: { 1: "", 2: "", }, }, }, { input: [ { "1": "", "2": "", }, { "3": "", "4": "", "5": "", }, { "1": "", "2": "", "3": "", "4": "", }, "test", 1, true, {}, undefined, null, ], output: { item: { 1: "", 2: "", 3: "", 4: "", 5: "", }, }, }, ].forEach((d) => { const widget = {}; set(widget, `${EVAL_VALUE_PATH}.sourceData`, d.input); expect( getLabelValueAdditionalAutocompleteData(widget as WidgetProps), ).toEqual(d.output); }); }); test("should test that empty item is generated for invalid values", () => { [[], "", null, undefined, {}, true, 1].forEach((d) => { const widget = {}; set(widget, `${EVAL_VALUE_PATH}.sourceData`, d); expect( getLabelValueAdditionalAutocompleteData(widget as WidgetProps), ).toEqual({ item: {}, }); }); }); });
1,975
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/SingleSelectTreeWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/SingleSelectTreeWidget/widget/derived.test.ts
import _ from "lodash"; import { flat } from "widgets/WidgetUtils"; import derivedProperty from "./derived"; const options = [ { label: "Blue", value: "BLUE", children: [ { label: "Dark Blue", value: "DARK BLUE", }, { label: "Light Blue", value: "LIGHT BLUE", }, ], }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, { label: "0", value: 0, }, { label: "1", value: 1, }, ]; const flattenedOptions = flat(options); describe("Derived property - TreeSelect Widget", () => { describe("#getIsValid", () => { it("return true when isRequired false and selectedOptionValue is empty string", () => { const isValid = derivedProperty.getIsValid( { isRequired: false, selectedOptionValue: "", }, null, _, ); expect(isValid).toBeTruthy(); }); it("return true when isRequired true and selectedOptionValue is not empty", () => { const isValid = derivedProperty.getIsValid( { selectedOptionValue: "GREEN", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("return true when isRequired true and selectedOptionValue is not empty", () => { const isValid = derivedProperty.getIsValid( { selectedOptionValue: 0, isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("return false when isRequired true and selectedOptionValue is empty", () => { const isValid = derivedProperty.getIsValid( { selectedOptionValue: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); }); }); describe("#getSelectedOptionValue", () => { it("selectedOptionValue should have a value if defaultValue(String) is in option", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { selectedOption: "GREEN", flattenedOptions, }, null, _, ); expect(selectedOptionValue).toBe("GREEN"); }); it("selectedOptionValue should have a value if defaultValue(Number) is in option", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { selectedOption: 1, flattenedOptions, }, null, _, ); expect(selectedOptionValue).toBe(1); }); it("selectedOptionValue should not have a value if defaultValue(string) is not in option ", () => { const selectedOptionValue = derivedProperty.getSelectedOptionValue( { value: "YELLOW", flattenedOptions, }, null, _, ); expect(selectedOptionValue).toBe(""); }); }); describe("#getSelectedOptionLabel", () => { it("selectedOptionLabel should have a value if defaultValue(String) is in option", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: "GREEN", selectedLabel: "GREEN", flattenedOptions, }, null, _, ); expect(selectedOptionLabel).toBe("Green"); }); it("selectedOptionLabel should have a value if defaultValue(Number) is in option", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: 0, selectedLabel: 0, flattenedOptions, }, null, _, ); expect(selectedOptionLabel).toBe("0"); }); it("selectedOptionLabel should not have a value if defaultValue(string) is not in option", () => { const selectedOptionLabel = derivedProperty.getSelectedOptionLabel( { selectedOptionValue: "", selectedLabel: "YELLOW", flattenedOptions, }, null, _, ); expect(selectedOptionLabel).toBe(""); }); }); });
1,996
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget/component/CommonUtilities.test.ts
import { sortTableFunction, transformTableDataIntoCsv, } from "./CommonUtilities"; import type { TableColumnProps } from "./Constants"; import { ColumnTypes } from "./Constants"; describe("TableUtilities", () => { it("works as expected for sort table rows", () => { const filteredTableData: Array<Record<string, unknown>> = [ { url: "https://www.google.com", }, { url: "https://www.amazon.com", }, ]; const expected: Array<Record<string, unknown>> = [ { url: "https://www.amazon.com", }, { url: "https://www.google.com", }, ]; const sortedTableData = sortTableFunction( filteredTableData, ColumnTypes.URL, "url", true, ); expect(sortedTableData).toStrictEqual(expected); }); }); describe("TransformTableDataIntoArrayOfArray", () => { const columns: TableColumnProps[] = [ { Header: "Id", accessor: "id", minWidth: 60, draggable: true, metaProperties: { isHidden: false, type: "string", }, columnProperties: { id: "id", label: "Id", columnType: "string", isVisible: true, index: 0, width: 60, isDerived: false, computedValue: "", }, }, ]; it("work as expected", () => { const data = [ { id: "abc", }, { id: "xyz", }, ]; const csvData = transformTableDataIntoCsv({ columns, data, }); const expectedCsvData = [["Id"], ["abc"], ["xyz"]]; expect(JSON.stringify(csvData)).toStrictEqual( JSON.stringify(expectedCsvData), ); }); it("work as expected with newline", () => { const data = [ { id: "abc\ntest", }, { id: "xyz", }, ]; const csvData = transformTableDataIntoCsv({ columns, data, }); const expectedCsvData = [["Id"], ["abc test"], ["xyz"]]; expect(JSON.stringify(csvData)).toStrictEqual( JSON.stringify(expectedCsvData), ); }); it("work as expected with comma", () => { const data = [ { id: "abc,test", }, { id: "xyz", }, ]; const csvData = transformTableDataIntoCsv({ columns, data, }); const expectedCsvData = [["Id"], ['"abc,test"'], ["xyz"]]; expect(JSON.stringify(csvData)).toStrictEqual( JSON.stringify(expectedCsvData), ); }); });
1,998
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget/component/Constants.test.ts
import { ConditionFunctions } from "./Constants"; import moment from "moment"; describe("ConditionFunctions Constants", () => { it("works as expected for isExactly", () => { const conditionFunction = ConditionFunctions["isExactly"]; expect(conditionFunction("test", "test")).toStrictEqual(true); }); it("works as expected for isExactly", () => { const conditionFunction = ConditionFunctions["isExactly"]; expect(conditionFunction("test", "random")).toStrictEqual(false); }); it("works as expected for empty", () => { const conditionFunction = ConditionFunctions["empty"]; expect(conditionFunction("", "")).toStrictEqual(true); }); it("works as expected for notEmpty", () => { const conditionFunction = ConditionFunctions["notEmpty"]; expect(conditionFunction("test", "")).toStrictEqual(true); }); it("works as expected for notEqualTo", () => { const conditionFunction = ConditionFunctions["notEqualTo"]; expect(conditionFunction("test", "random")).toStrictEqual(true); }); it("works as expected for isEqualTo", () => { const conditionFunction = ConditionFunctions["isEqualTo"]; expect(conditionFunction("test", "test")).toStrictEqual(true); }); it("works as expected for lessThan", () => { const conditionFunction = ConditionFunctions["lessThan"]; expect(conditionFunction(50, 100)).toStrictEqual(true); }); it("works as expected for lessThanEqualTo", () => { const conditionFunction = ConditionFunctions["lessThanEqualTo"]; expect(conditionFunction(50, 50)).toStrictEqual(true); }); it("works as expected for greaterThan", () => { const conditionFunction = ConditionFunctions["greaterThan"]; expect(conditionFunction(100, 50)).toStrictEqual(true); }); it("works as expected for contains", () => { const conditionFunction = ConditionFunctions["contains"]; expect(conditionFunction("random", "and")).toStrictEqual(true); }); it("works as expected for startsWith", () => { const conditionFunction = ConditionFunctions["startsWith"]; expect(conditionFunction("tested", "test")).toStrictEqual(true); }); it("works as expected for endsWith", () => { const conditionFunction = ConditionFunctions["endsWith"]; expect(conditionFunction("subtest", "test")).toStrictEqual(true); expect(conditionFunction("subtest", "t")).toStrictEqual(true); }); it("works as expected for is", () => { const conditionFunction = ConditionFunctions["is"]; const date1 = moment(); expect(conditionFunction(date1, date1)).toStrictEqual(true); }); it("works as expected for isNot", () => { const conditionFunction = ConditionFunctions["isNot"]; const date1 = moment(); const date2 = moment().add(1, "day"); expect(conditionFunction(date1, date2)).toStrictEqual(true); }); it("works as expected for isAfter", () => { const conditionFunction = ConditionFunctions["isAfter"]; const date1 = moment(); const date2 = moment().add(1, "day"); expect(conditionFunction(date1, date2)).toStrictEqual(true); }); it("works as expected for isBefore", () => { const conditionFunction = ConditionFunctions["isBefore"]; const date1 = moment(); const date2 = moment().subtract(1, "day"); expect(conditionFunction(date1, date2)).toStrictEqual(true); }); });
2,009
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget/component/TableHelpers.test.ts
import type { ColumnProperties } from "./Constants"; import { reorderColumns } from "./TableHelpers"; import { getCurrentRowBinding } from "widgets/TableWidget/constants"; const MOCK_COLUMNS: Record<string, ColumnProperties> = { id: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.id"), textSize: "PARAGRAPH", index: 0, isVisible: true, label: "id", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "id", verticalAlignment: "CENTER", }, name: { index: 1, width: 150, id: "name", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "name", computedValue: getCurrentRowBinding("Table1", "currentRow.name"), }, createdAt: { index: 2, width: 150, id: "createdAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "createdAt", computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"), }, updatedAt: { index: 3, width: 150, id: "updatedAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "updatedAt", computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"), }, status: { index: 4, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "status", computedValue: getCurrentRowBinding("Table1", "currentRow.status"), }, gender: { index: 5, width: 150, id: "gender", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "gender", computedValue: getCurrentRowBinding("Table1", "currentRow.gender"), }, avatar: { index: 6, width: 150, id: "avatar", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "avatar", computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"), }, address: { index: 8, width: 150, id: "address", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), }, role: { index: 9, id: "role", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, width: 150, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), }, dob: { index: 10, width: 150, id: "dob", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "dob", computedValue: getCurrentRowBinding("Table1", "currentRow.dob"), }, phoneNo: { index: 11, width: 150, id: "phoneNo", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "phoneNo", computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"), }, email: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.email"), textSize: "PARAGRAPH", index: 1, isVisible: true, label: "email", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "email", verticalAlignment: "CENTER", }, }; describe("Validate Helpers", () => { it("correctly reorders columns", () => { const columnOrder = [ "phoneNo", "id", "name", "createdAt", "updatedAt", "status", "gender", "avatar", "email", "address", "role", "dob", ]; const expected = { phoneNo: { index: 0, width: 150, id: "phoneNo", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "phoneNo", computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"), }, id: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.id"), textSize: "PARAGRAPH", index: 1, isVisible: true, label: "id", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "id", verticalAlignment: "CENTER", }, name: { index: 2, width: 150, id: "name", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "name", computedValue: getCurrentRowBinding("Table1", "currentRow.name"), }, createdAt: { index: 3, width: 150, id: "createdAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "createdAt", computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"), }, updatedAt: { index: 4, width: 150, id: "updatedAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "updatedAt", computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"), }, status: { index: 5, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "status", computedValue: getCurrentRowBinding("Table1", "currentRow.status"), }, gender: { index: 6, width: 150, id: "gender", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "gender", computedValue: getCurrentRowBinding("Table1", "currentRow.gender"), }, avatar: { index: 7, width: 150, id: "avatar", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "avatar", computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"), }, email: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.email"), textSize: "PARAGRAPH", index: 8, isVisible: true, label: "email", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "email", verticalAlignment: "CENTER", }, address: { index: 9, width: 150, id: "address", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), }, role: { index: 10, id: "role", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, width: 150, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), }, dob: { index: 11, width: 150, id: "dob", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "dob", computedValue: getCurrentRowBinding("Table1", "currentRow.dob"), }, }; const result = reorderColumns(MOCK_COLUMNS, columnOrder); expect(expected).toEqual(result); }); it("Ignores duplicates in column order and includes all columns", () => { const columnOrder = [ "phoneNo", "id", "name", "createdAt", "updatedAt", "status", "status", "gender", "avatar", "email", ]; const expected = { phoneNo: { index: 0, width: 150, id: "phoneNo", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "phoneNo", computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"), }, id: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.id"), textSize: "PARAGRAPH", index: 1, isVisible: true, label: "id", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "id", verticalAlignment: "CENTER", }, name: { index: 2, width: 150, id: "name", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "name", computedValue: getCurrentRowBinding("Table1", "currentRow.name"), }, createdAt: { index: 3, width: 150, id: "createdAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "createdAt", computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"), }, updatedAt: { index: 4, width: 150, id: "updatedAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "updatedAt", computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"), }, status: { index: 5, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "status", computedValue: getCurrentRowBinding("Table1", "currentRow.status"), }, gender: { index: 6, width: 150, id: "gender", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "gender", computedValue: getCurrentRowBinding("Table1", "currentRow.gender"), }, avatar: { index: 7, width: 150, id: "avatar", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "avatar", computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"), }, email: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.email"), textSize: "PARAGRAPH", index: 8, isVisible: true, label: "email", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "email", verticalAlignment: "CENTER", }, address: { index: 9, width: 150, id: "address", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), }, role: { index: 10, id: "role", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, width: 150, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), }, dob: { index: 11, width: 150, id: "dob", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "dob", computedValue: getCurrentRowBinding("Table1", "currentRow.dob"), }, }; const result = reorderColumns(MOCK_COLUMNS, columnOrder); expect(expected).toEqual(result); }); });
2,013
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget/component/TableUtilities.test.tsx
import { renderCell } from "./TableUtilities"; import { ColumnTypes } from "widgets/TableWidget/component/Constants"; describe("Test table columnType Image render", () => { it("columnType Image accepts single image url and renders image correctly", () => { const value = "http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg"; const expected = [ "http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg", ]; const ImageCellComponent = renderCell( value, ColumnTypes.IMAGE, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); const result = ImageCellComponent.props.children.map((imageDiv: any) => { return imageDiv.props.children.props.style.backgroundImage .slice(4, -1) .replace(/"/g, ""); }); expect(expected).toEqual(result); }); it("columnType Image accepts single base64 url and renders image correctly", () => { const value = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; const expected = [ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==", ]; const ImageCellComponent = renderCell( value, ColumnTypes.IMAGE, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); const result = ImageCellComponent.props.children.map((imageDiv: any) => { return imageDiv.props.children.props.style.backgroundImage .slice(4, -1) .replace(/"/g, ""); }); expect(expected).toEqual(result); }); it("columnType Image accepts comma separeted image urls and renders all images correctly", () => { const value = "http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg,http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg,http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg"; const expected = [ "http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg", "http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg", "http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg", ]; const ImageCellComponent = renderCell( value, ColumnTypes.IMAGE, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); const result = ImageCellComponent.props.children.map((imageDiv: any) => { return imageDiv.props.children.props.style.backgroundImage .slice(4, -1) .replace(/"/g, ""); }); expect(expected).toEqual(result); }); it("columnType Image accepts comma separeted image urls that has base64 image and renders images correctly", () => { const value = "http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg,data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; const expected = [ "http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==", ]; const ImageCellComponent = renderCell( value, ColumnTypes.IMAGE, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); const result = ImageCellComponent.props.children.map((imageDiv: any) => { return imageDiv.props.children.props.style.backgroundImage .slice(4, -1) .replace(/"/g, ""); }); expect(expected).toEqual(result); }); it("columnType Image accepts image url that may have incorrect use of comma and renders image correctly", () => { const value = "http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg, "; const expected = [ "http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg", undefined, ]; const ImageCellComponent = renderCell( value, ColumnTypes.IMAGE, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); const result = ImageCellComponent.props.children.map((imageDiv: any) => { // check and get img url if exist const imageDivProps = imageDiv.props.children.props; if (imageDivProps) { return imageDivProps.style.backgroundImage .slice(4, -1) .replace(/"/g, ""); } else { return undefined; } }); expect(expected).toEqual(result); }); it("columnType Text accepts undefined value and render empty string ", () => { const value = undefined; const expected = ""; const renderedCell = renderCell( value, ColumnTypes.TEXT, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); expect(expected).toEqual(renderedCell.props.children); }); it("columnType Text accepts null value and render empty string ", () => { const value = null; const expected = ""; const renderedCell = renderCell( value, ColumnTypes.TEXT, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); expect(expected).toEqual(renderedCell.props.children); }); it("columnType Number accepts 0 as value and renders 0 ", () => { const value = 0; const expected = "0"; const renderedCell = renderCell( value, ColumnTypes.NUMBER, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); expect(expected).toEqual(renderedCell.props.children); }); it("columnType Number accepts NaN as value and renders empty string ", () => { const value = NaN; const expected = ""; const renderedCell = renderCell( value, ColumnTypes.NUMBER, false, // @ts-expect-error: other Props are missing { isCellVisible: true }, 930, true, ); expect(expected).toEqual(renderedCell.props.children); }); });
2,019
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget/widget/getTableColumns.test.tsx
import { getPropertyValue } from "./getTableColumns"; describe("getTableColumns", () => { describe("getPropertyValue", () => { it("should test that object value is processed properly", () => { const obj = { test: "someRandomTestValue", }; expect(getPropertyValue(obj, 0, true)).toBe(obj); }); it("should test that array value is processed properly", () => { const arr = ["test", undefined, null, ""]; expect(getPropertyValue(arr, 0, true)).toBe("test"); expect(getPropertyValue(arr, 0, false)).toBe("TEST"); expect(getPropertyValue(arr, 1, false)).toBe(undefined); expect(getPropertyValue(arr, 2, false)).toBe(null); expect(getPropertyValue(arr, 3, false)).toBe(""); }); it("should test that primitive values are processed properly", () => { expect(getPropertyValue("test", 0, true)).toBe("test"); expect(getPropertyValue("test", 0, false)).toBe("TEST"); expect(getPropertyValue(1, 0, true)).toBe("1"); expect(getPropertyValue(1, 0, false)).toBe("1"); expect(getPropertyValue(true, 0, true)).toBe("true"); expect(getPropertyValue(true, 0, false)).toBe("TRUE"); }); it("should test that falsy are processes properly", () => { expect(getPropertyValue("", 0, true)).toBe(""); expect(getPropertyValue(null, 0, true)).toBe(null); expect(getPropertyValue(undefined, 0, true)).toBe(undefined); }); }); });
2,024
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget/widget/propertyConfig.test.ts
import TableWidget from "./index"; describe("unit test case for property config pane", () => { it("case: check tooltip text for total record count property exists", () => { const generalSection: any = TableWidget.getPropertyPaneConfig().filter( (section: any) => section.sectionName === "General", ); const totalRecordsCount = generalSection[0].children.filter( (child: any) => child.propertyName === "totalRecordsCount", )[0]; expect(totalRecordsCount.helpText).toEqual( "It stores the total no. of rows in the table. Helps in calculating the no. of pages that further allows to enable or disable the next/previous control in pagination.", ); }); });
2,026
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget/widget/propertyUtils.test.ts
import { defaultSelectedRowValidation, updateIconNameHook, } from "./propertyUtils"; import _ from "lodash"; const tableWProps = { multiRowSelection: false, widgetName: "Table1", defaultPageSize: 0, columnOrder: ["step", "task", "status", "action"], isVisibleDownload: true, dynamicPropertyPathList: [], displayName: "Table", iconSVG: "/static/media/icon.db8a9cbd.svg", topRow: 54, bottomRow: 82, isSortable: true, parentRowSpace: 10, type: "TABLE_WIDGET", defaultSelectedRow: "0", hideCard: false, parentColumnSpace: 25.6875, dynamicTriggerPathList: [], dynamicBindingPathList: [ { key: "primaryColumns.step.computedValue", }, { key: "primaryColumns.task.computedValue", }, { key: "primaryColumns.status.computedValue", }, { key: "primaryColumns.action.computedValue", }, ], leftColumn: 25, primaryColumns: { step: { index: 0, width: 150, id: "step", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "step", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.step))}}", }, task: { index: 1, width: 150, id: "task", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "task", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.task))}}", }, status: { index: 2, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDerived: false, label: "status", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.status))}}", }, action: { index: 3, width: 150, id: "action", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "button", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isCellVisible: true, isDisabled: false, isDerived: false, label: "action", onClick: "{{currentRow.step === '#1' ? showAlert('Done', 'success') : currentRow.step === '#2' ? navigateTo('https://docs.appsmith.com/core-concepts/connecting-to-data-sources/querying-a-database',undefined,'NEW_WINDOW') : navigateTo('https://docs.appsmith.com/core-concepts/displaying-data-read/display-data-tables',undefined,'NEW_WINDOW')}}", computedValue: "{{Table1.sanitizedTableData.map((currentRow) => ( currentRow.action))}}", }, }, delimiter: ",", key: "fzi9jh5j7j", derivedColumns: {}, rightColumn: 50, textSize: "PARAGRAPH", widgetId: "2tk8bgzwaz", isVisibleFilters: true, tableData: [ { step: "#1", task: "Drop a table", status: "✅", action: "", }, { step: "#2", task: "Create a query fetch_users with the Mock DB", status: "--", action: "", }, { step: "#3", task: "Bind the query using => fetch_users.data", status: "--", action: "", }, ], isVisible: true, label: "Data", searchKey: "", version: 3, totalRecordsCount: 0, parentId: "0", renderMode: "CANVAS", isLoading: false, horizontalAlignment: "LEFT", isVisibleSearch: true, isVisiblePagination: true, verticalAlignment: "CENTER", columnSizeMap: { task: 245, step: 62, status: 75, }, childStylesheet: { button: { buttonColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, menuButton: { menuColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, iconButton: { menuColor: "{{appsmith.theme.colors.primaryColor}}", borderRadius: "{{appsmith.theme.borderRadius.appBorderRadius}}", boxShadow: "none", }, }, }; describe("unit test case for property utils", () => { it("case: check if the defaultSelectedRowValiation returns parsed value as undefined", () => { const value = defaultSelectedRowValidation("", tableWProps as any, _); expect(value.isValid).toBeTruthy(); expect(value.parsed).toEqual(undefined); }); it("case: when columnType is menuButton, iconName should be empty string", () => { const propertiesToUpdate = updateIconNameHook( tableWProps as any, "primaryColumns.action.columnType", "menuButton", ); const output = [ { propertyPath: "derivedColumns.action.menuColor", propertyValue: "{{Table1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.colors.primaryColor)))}}", }, { propertyPath: "primaryColumns.action.menuColor", propertyValue: "{{Table1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.colors.primaryColor)))}}", }, { propertyPath: "derivedColumns.action.borderRadius", propertyValue: "{{Table1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.borderRadius.appBorderRadius)))}}", }, { propertyPath: "primaryColumns.action.borderRadius", propertyValue: "{{Table1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.borderRadius.appBorderRadius)))}}", }, { propertyPath: "derivedColumns.action.boxShadow", propertyValue: '{{Table1.sanitizedTableData.map((currentRow) => ( "none"))}}', }, { propertyPath: "primaryColumns.action.boxShadow", propertyValue: '{{Table1.sanitizedTableData.map((currentRow) => ( "none"))}}', }, { propertyPath: "primaryColumns.action.columnType", propertyValue: "menuButton", }, { propertyPath: "primaryColumns.action.iconName", propertyValue: "", }, ]; expect(propertiesToUpdate).toEqual(output); }); it("case: when columnType is iconButton, iconName value should be add", () => { const propertiesToUpdate = updateIconNameHook( tableWProps as any, "primaryColumns.action.columnType", "iconButton", ); const output = [ { propertyPath: "derivedColumns.action.menuColor", propertyValue: "{{Table1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.colors.primaryColor)))}}", }, { propertyPath: "primaryColumns.action.menuColor", propertyValue: "{{Table1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.colors.primaryColor)))}}", }, { propertyPath: "derivedColumns.action.borderRadius", propertyValue: "{{Table1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.borderRadius.appBorderRadius)))}}", }, { propertyPath: "primaryColumns.action.borderRadius", propertyValue: "{{Table1.sanitizedTableData.map((currentRow) => ( (appsmith.theme.borderRadius.appBorderRadius)))}}", }, { propertyPath: "derivedColumns.action.boxShadow", propertyValue: '{{Table1.sanitizedTableData.map((currentRow) => ( "none"))}}', }, { propertyPath: "primaryColumns.action.boxShadow", propertyValue: '{{Table1.sanitizedTableData.map((currentRow) => ( "none"))}}', }, { propertyPath: "primaryColumns.action.columnType", propertyValue: "iconButton", }, { propertyPath: "primaryColumns.action.iconName", propertyValue: "add", }, ]; expect(propertiesToUpdate).toEqual(output); }); });
2,028
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidget/widget/utilities.test.ts
import { getOriginalRowIndex, selectRowIndex, selectRowIndices, } from "./utilities"; describe("getOriginalRowIndex", () => { it("With no previous data ", () => { const oldTableData = [ { step: "#1", task: " a fetch_users wih the Mock DB", status: "--", }, { step: "#2", task: " a fetch_users wih the Mock DB", status: "--", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", }, ]; const newTableData: Record<string, unknown>[] = []; const selectedRowIndex = 1; const result = getOriginalRowIndex( oldTableData, newTableData, selectedRowIndex, ); const expected = undefined; expect(result).toStrictEqual(expected); }); it("With no new data", () => { const oldTableData: Record<string, unknown>[] = []; const newTableData = [ { step: "#1", task: " a fetch_users wih the Mock DB", status: "--", }, { step: "#2", task: " a fetch_users wih the Mock DB", status: "--", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", }, ]; const selectedRowIndex = 1; const result = getOriginalRowIndex( oldTableData, newTableData, selectedRowIndex, ); const expected = undefined; expect(result).toStrictEqual(expected); }); it("With no selectedRowIndex", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const result = getOriginalRowIndex(oldTableData, newTableData, undefined); const expected = undefined; expect(result).toStrictEqual(expected); }); it("With no data", () => { const oldTableData = undefined; const newTableData = undefined; const selectedRowIndex = 1; const result = getOriginalRowIndex( oldTableData as any as Array<Record<string, unknown>>, newTableData as any as Array<Record<string, unknown>>, selectedRowIndex, ); const expected = undefined; expect(result).toStrictEqual(expected); }); }); describe("selectRowIndex", () => { it("With new Data", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const selectedRowIndexProp = 0; const defaultSelectedRow = 0; const result = selectRowIndex( oldTableData, newTableData, defaultSelectedRow, selectedRowIndexProp, "step", ); expect(result).toStrictEqual(0); }); }); describe("selectRowIndices", () => { it("With no selected index", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const defaultSelectedRow = [0]; const result = selectRowIndices( oldTableData, newTableData, defaultSelectedRow, [], undefined, ); expect(result).toEqual([0]); }); });
2,033
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2/component/Constants.test.ts
import { ConditionFunctions } from "./Constants"; import moment from "moment"; describe("ConditionFunctions Constants", () => { it("works as expected for isExactly", () => { const conditionFunction = ConditionFunctions["isExactly"]; expect(conditionFunction("test", "test")).toStrictEqual(true); }); it("works as expected for isExactly", () => { const conditionFunction = ConditionFunctions["isExactly"]; expect(conditionFunction("test", "random")).toStrictEqual(false); }); it("works as expected for empty", () => { const conditionFunction = ConditionFunctions["empty"]; expect(conditionFunction("", "")).toStrictEqual(true); }); it("works as expected for notEmpty", () => { const conditionFunction = ConditionFunctions["notEmpty"]; expect(conditionFunction("test", "")).toStrictEqual(true); }); it("works as expected for notEqualTo", () => { const conditionFunction = ConditionFunctions["notEqualTo"]; expect(conditionFunction("test", "random")).toStrictEqual(true); }); it("works as expected for isEqualTo", () => { const conditionFunction = ConditionFunctions["isEqualTo"]; expect(conditionFunction("test", "test")).toStrictEqual(true); }); it("works as expected for lessThan", () => { const conditionFunction = ConditionFunctions["lessThan"]; expect(conditionFunction(50, 100)).toStrictEqual(true); }); it("works as expected for lessThanEqualTo", () => { const conditionFunction = ConditionFunctions["lessThanEqualTo"]; expect(conditionFunction(50, 50)).toStrictEqual(true); }); it("works as expected for greaterThan", () => { const conditionFunction = ConditionFunctions["greaterThan"]; expect(conditionFunction(100, 50)).toStrictEqual(true); }); it("works as expected for contains", () => { const conditionFunction = ConditionFunctions["contains"]; expect(conditionFunction("random", "and")).toStrictEqual(true); }); it("works as expected for startsWith", () => { const conditionFunction = ConditionFunctions["startsWith"]; expect(conditionFunction("tested", "test")).toStrictEqual(true); }); it("works as expected for endsWith", () => { const conditionFunction = ConditionFunctions["endsWith"]; expect(conditionFunction("subtest", "test")).toStrictEqual(true); expect(conditionFunction("subtest", "t")).toStrictEqual(true); }); it("works as expected for is", () => { const conditionFunction = ConditionFunctions["is"]; const date1 = moment(); expect(conditionFunction(date1, date1)).toStrictEqual(true); }); it("works as expected for isNot", () => { const conditionFunction = ConditionFunctions["isNot"]; const date1 = moment(); const date2 = moment().add(1, "day"); expect(conditionFunction(date1, date2)).toStrictEqual(true); }); it("works as expected for isAfter", () => { const conditionFunction = ConditionFunctions["isAfter"]; const date1 = moment(); const date2 = moment().add(1, "day"); expect(conditionFunction(date1, date2)).toStrictEqual(true); }); it("works as expected for isBefore", () => { const conditionFunction = ConditionFunctions["isBefore"]; const date1 = moment(); const date2 = moment().subtract(1, "day"); expect(conditionFunction(date1, date2)).toStrictEqual(true); }); });
2,056
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2/component
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2/component/cellComponents/PlainTextCell.test.tsx
import { getCellText } from "./PlainTextCell"; import { ColumnTypes } from "widgets/TableWidgetV2/constants"; describe("DefaultRendere - ", () => { describe("getCellText", () => { it("should test with different values", () => { [ { value: "#1", cellProperties: { displayText: "test" }, columnType: ColumnTypes.TEXT, expected: "#1", }, { value: 1, cellProperties: { displayText: "test" }, columnType: ColumnTypes.TEXT, expected: "1", }, { value: true, cellProperties: { displayText: "test" }, columnType: ColumnTypes.TEXT, expected: "true", }, { value: undefined, cellProperties: { displayText: "test" }, columnType: ColumnTypes.TEXT, expected: "", }, { value: null, cellProperties: { displayText: "test" }, columnType: ColumnTypes.TEXT, expected: "", }, { value: NaN, cellProperties: { displayText: "test" }, columnType: ColumnTypes.TEXT, expected: "", }, { value: "www.appsmith.com", cellProperties: { displayText: "test" }, columnType: ColumnTypes.URL, expected: "test", }, { value: { test: 1 }, cellProperties: { displayText: "test" }, columnType: ColumnTypes.TEXT, expected: "[object Object]", }, ].forEach((testValue) => { expect( getCellText( testValue.value, testValue.columnType, testValue.cellProperties.displayText, ), ).toEqual(testValue.expected); }); }); }); });
2,069
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2/component/header
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2/component/header/actions/Utilities.test.ts
import { transformTableDataIntoCsv } from "./Utilities"; import type { TableColumnProps } from "../../Constants"; import { ColumnTypes } from "widgets/TableWidgetV2/constants"; describe("TransformTableDataIntoArrayOfArray", () => { const columns: TableColumnProps[] = [ { Header: "Id", id: "id", alias: "id", accessor: "id", minWidth: 60, draggable: true, metaProperties: { isHidden: false, type: ColumnTypes.TEXT, }, columnProperties: { id: "id", originalId: "id", alias: "id", label: "Id", columnType: "string", isVisible: true, index: 0, width: 60, isDerived: false, computedValue: "", isCellEditable: false, isEditable: false, allowCellWrapping: false, }, }, ]; it("work as expected", () => { const data = [ { id: "abc", }, { id: "xyz", }, ]; const csvData = transformTableDataIntoCsv({ columns, data, }); const expectedCsvData = [["Id"], ["abc"], ["xyz"]]; expect(JSON.stringify(csvData)).toStrictEqual( JSON.stringify(expectedCsvData), ); }); it("work as expected with newline", () => { const data = [ { id: "abc\ntest", }, { id: "xyz", }, ]; const csvData = transformTableDataIntoCsv({ columns, data, }); const expectedCsvData = [["Id"], ["abc test"], ["xyz"]]; expect(JSON.stringify(csvData)).toStrictEqual( JSON.stringify(expectedCsvData), ); }); it("work as expected with comma", () => { const data = [ { id: "abc,test", }, { id: "xyz", }, ]; const csvData = transformTableDataIntoCsv({ columns, data, }); const expectedCsvData = [["Id"], ['"abc,test"'], ["xyz"]]; expect(JSON.stringify(csvData)).toStrictEqual( JSON.stringify(expectedCsvData), ); }); });
2,083
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2/widget/propertyUtils.test.ts
import { totalRecordsCountValidation, uniqueColumnNameValidation, updateColumnStyles, updateColumnOrderHook, getBasePropertyPath, hideByColumnType, uniqueColumnAliasValidation, updateCustomColumnAliasOnLabelChange, selectColumnOptionsValidation, allowedFirstDayOfWeekRange, } from "./propertyUtils"; import _ from "lodash"; import type { ColumnTypes, TableWidgetProps } from "../constants"; import { StickyType } from "../component/Constants"; describe("PropertyUtils - ", () => { it("totalRecordsCountValidation - should test with all possible values", () => { const ERROR_MESSAGE = [ { name: "ValidationError", message: "This value must be a number" }, ]; const values = [ [ undefined, { isValid: true, parsed: 0, messages: [], }, ], [ null, { isValid: true, parsed: 0, messages: [], }, ], [ "", { isValid: true, parsed: 0, messages: [], }, ], [ {}, { isValid: false, parsed: 0, messages: ERROR_MESSAGE, }, ], [ [], { isValid: false, parsed: 0, messages: ERROR_MESSAGE, }, ], [ "test", { isValid: false, parsed: 0, messages: ERROR_MESSAGE, }, ], [ "1", { isValid: true, parsed: 1, messages: [], }, ], [ 1, { isValid: true, parsed: 1, messages: [], }, ], ]; values.forEach(([input, expected]) => { expect( totalRecordsCountValidation(input, {} as TableWidgetProps, _), ).toEqual(expected); }); }); it("uniqueColumnNameValidation - should test with all possible values", () => { let value = [ { label: "column1", }, { label: "column2", }, { label: "column3", }, ]; expect( uniqueColumnNameValidation(value, {} as TableWidgetProps, _), ).toEqual({ isValid: true, parsed: value, messages: [""], }); value = [ { label: "column1", }, { label: "column2", }, { label: "column1", }, ]; expect( uniqueColumnNameValidation(value, {} as TableWidgetProps, _), ).toEqual({ isValid: false, parsed: value, messages: ["Column names should be unique."], }); }); it("updateColumnStyles - should test with all possible values", () => { let props: any = { primaryColumns: { 1: { id: 1, style: "someRandomStyleValue", }, 2: { id: 2, style: "someRandomStyleValue", }, 3: { id: 3, style: "someRandomStyleValue", }, }, }; expect( updateColumnStyles( props as any as TableWidgetProps, "style", "someOtherRandomStyleValue", ), ).toEqual([ { propertyPath: "primaryColumns.1.style", propertyValue: "someOtherRandomStyleValue", }, { propertyPath: "primaryColumns.2.style", propertyValue: "someOtherRandomStyleValue", }, { propertyPath: "primaryColumns.3.style", propertyValue: "someOtherRandomStyleValue", }, ]); props = { dynamicBindingPathList: [ { key: "primaryColumns.3.style", }, ], primaryColumns: { 1: { id: 1, style: "someRandomStyleValue", }, 2: { id: 2, style: "someRandomStyleValue", }, 3: { id: 3, style: "someRandomStyleValue", }, }, }; expect( updateColumnStyles( props as any as TableWidgetProps, "style", "someOtherRandomStyleValue", ), ).toEqual([ { propertyPath: "primaryColumns.1.style", propertyValue: "someOtherRandomStyleValue", }, { propertyPath: "primaryColumns.2.style", propertyValue: "someOtherRandomStyleValue", }, ]); expect( updateColumnStyles( props as any as TableWidgetProps, "", "someOtherRandomStyleValue", ), ).toEqual(undefined); expect( updateColumnStyles( {} as any as TableWidgetProps, "style", "someOtherRandomStyleValue", ), ).toEqual(undefined); expect( updateColumnStyles( {} as any as TableWidgetProps, "", "someOtherRandomStyleValue", ), ).toEqual(undefined); }); it("updateColumnOrderHook - should test with all possible values", () => { const defaultStickyValuesForPrimaryCols = { column1: { sticky: StickyType.NONE, }, column2: { sticky: StickyType.NONE, }, column3: { sticky: StickyType.NONE, }, }; expect( updateColumnOrderHook( { columnOrder: ["column1", "column2"], primaryColumns: defaultStickyValuesForPrimaryCols, } as any as TableWidgetProps, "primaryColumns.column3", { id: "column3", }, ), ).toEqual([ { propertyPath: "columnOrder", propertyValue: ["column1", "column2", "column3"], }, { propertyPath: "primaryColumns.column3", propertyValue: { id: "column3", labelColor: "#FFFFFF", }, }, ]); expect( updateColumnOrderHook( { columnOrder: ["column1", "column2"], } as any as TableWidgetProps, "", { id: "column3", }, ), ).toEqual(undefined); expect( updateColumnOrderHook({} as any as TableWidgetProps, "", { id: "column3", }), ).toEqual(undefined); expect( updateColumnOrderHook( { columnOrder: ["column1", "column2"], } as any as TableWidgetProps, "primaryColumns.column3.iconAlignment", { id: "column3", }, ), ).toEqual(undefined); }); it("getBasePropertyPath - should test with all possible values", () => { expect(getBasePropertyPath("primaryColumns.test")).toBe("primaryColumns"); expect(getBasePropertyPath("primaryColumns.test.style")).toBe( "primaryColumns.test", ); expect(getBasePropertyPath("")).toBe(undefined); expect(getBasePropertyPath("primaryColumns")).toBe(undefined); }); describe("hideByColumnType - ", () => { it("should test with column type that should not be hidden", () => { const prop = { primaryColumns: { column: { columnType: "text", }, }, }; expect( hideByColumnType( prop as any as TableWidgetProps, "primaryColumns.column", ["text"] as ColumnTypes[], true, ), ).toBe(false); }); it("should test with column type that should be hidden", () => { const prop = { primaryColumns: { column: { columnType: "select", }, }, }; expect( hideByColumnType( prop as any as TableWidgetProps, "primaryColumns.column", ["text"] as ColumnTypes[], true, ), ).toBe(true); }); it("should test column that should be hidden, with full propertyPath", () => { const prop = { primaryColumns: { column: { columnType: "select", }, }, }; expect( hideByColumnType( prop as any as TableWidgetProps, "primaryColumns.column.buttonColor", ["Button"] as any as ColumnTypes[], ), ).toBe(true); }); it("should test column that should not be hidden, with full propertyPath", () => { const prop = { primaryColumns: { column: { columnType: "Button", }, }, }; expect( hideByColumnType( prop as any as TableWidgetProps, "primaryColumns.column.buttonColor", ["Button"] as any as ColumnTypes[], ), ).toBe(false); }); }); }); describe("uniqueColumnAliasValidation", () => { it("should validate that duplicate value is not allowed", () => { expect( uniqueColumnAliasValidation( "column", { primaryColumns: { column: { alias: "column", }, column1: { alias: "column", }, column2: { alias: "column2", }, }, } as unknown as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: "column", messages: ["Property names should be unique."], }); }); it("should validate that empty value is not allowed", () => { expect( uniqueColumnAliasValidation( "", { primaryColumns: { column: { alias: "column", }, column1: { alias: "column1", }, column2: { alias: "column2", }, }, } as unknown as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: "", messages: ["Property name should not be empty."], }); }); it("should validate that unique value is allowed", () => { expect( uniqueColumnAliasValidation( "column1", { primaryColumns: { column: { alias: "column", }, column1: { alias: "column1", }, column2: { alias: "column2", }, }, } as unknown as TableWidgetProps, _, ), ).toEqual({ isValid: true, parsed: "column1", messages: [""], }); }); }); describe("selectColumnOptionsValidation", () => { describe("- Array of label, values", () => { it("should check that for empty values are allowed", () => { ["", undefined, null].forEach((value) => { expect( selectColumnOptionsValidation(value, {} as TableWidgetProps, _), ).toEqual({ isValid: true, parsed: [], messages: [""], }); }); }); it("should check that value should be an array", () => { expect( selectColumnOptionsValidation("test", {} as TableWidgetProps, _), ).toEqual({ isValid: false, parsed: [], messages: [ `This value does not evaluate to type Array<{ "label": string | number, "value": string | number | boolean }>`, ], }); expect( selectColumnOptionsValidation(1, {} as TableWidgetProps, _), ).toEqual({ isValid: false, parsed: [], messages: [ `This value does not evaluate to type Array<{ "label": string | number, "value": string | number | boolean }>`, ], }); expect( selectColumnOptionsValidation([], {} as TableWidgetProps, _), ).toEqual({ isValid: true, parsed: [], messages: [""], }); }); it("should check that there are no null or undefined values", () => { expect( selectColumnOptionsValidation( [null, { label: "2", value: "1" }], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [], messages: [ `Invalid entry at index: 0. This value does not evaluate to type: { "label": string | number, "value": string | number | boolean }`, ], }); }); it("should check that value should be an array of objects", () => { expect( selectColumnOptionsValidation([1, 2], {} as TableWidgetProps, _), ).toEqual({ isValid: false, parsed: [1, 2], messages: [ `Invalid entry at index: 0. This value does not evaluate to type: { "label": string | number, "value": string | number | boolean }`, ], }); }); it("should check that each value should have label key", () => { expect( selectColumnOptionsValidation( [{ value: "1" }, { value: "2" }], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [{ value: "1" }, { value: "2" }], messages: [`Invalid entry at index: 0. Missing required key: label`], }); }); it("should check that each value should have value key", () => { expect( selectColumnOptionsValidation( [{ label: "1" }, { label: "2" }], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [{ label: "1" }, { label: "2" }], messages: [`Invalid entry at index: 0. Missing required key: value`], }); }); it("should check that each value should have unique value", () => { expect( selectColumnOptionsValidation( [ { label: "1", value: "1" }, { label: "2", value: "1" }, ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [ { label: "1", value: "1" }, { label: "2", value: "1" }, ], messages: [ "Duplicate values found for the following properties, in the array entries, that must be unique -- value.", ], }); }); it("should check that array of label, value witn invalid values", () => { expect( selectColumnOptionsValidation( [{ label: "1", value: [] }], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [{ label: "1", value: [] }], messages: [ "Invalid entry at index: 0. value does not evaluate to type string | number | boolean", ], }); expect( selectColumnOptionsValidation( [{ label: true, value: "1" }], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [{ label: true, value: "1" }], messages: [ "Invalid entry at index: 0. label does not evaluate to type string | number", ], }); }); it("should check that array of label, value is valid", () => { expect( selectColumnOptionsValidation( [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], messages: [""], }); expect( selectColumnOptionsValidation( [ { label: "1", value: 1 }, { label: "2", value: "2" }, ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [ { label: "1", value: 1 }, { label: "2", value: "2" }, ], messages: [""], }); expect( selectColumnOptionsValidation( [ { label: "1", value: true }, { label: "2", value: "2" }, ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [ { label: "1", value: true }, { label: "2", value: "2" }, ], messages: [""], }); expect( selectColumnOptionsValidation( [ { label: 1, value: true }, { label: "2", value: "2" }, ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [ { label: 1, value: true }, { label: "2", value: "2" }, ], messages: [""], }); }); }); describe("- Array of Array of label, values", () => { it("should check that value should be an array of arrays", () => { expect( selectColumnOptionsValidation([[1, 2], 1], {} as TableWidgetProps, _), ).toEqual({ isValid: false, parsed: [], messages: [ `This value does not evaluate to type Array<{ "label": string | number, "value": string | number | boolean }>`, ], }); }); it("should check that value should be an array of arrays of object", () => { expect( selectColumnOptionsValidation([[1, 2]], {} as TableWidgetProps, _), ).toEqual({ isValid: false, parsed: [[1, 2]], messages: [ `Invalid entry at Row: 0 index: 0. This value does not evaluate to type: { "label": string | number, "value": string | number | boolean }`, ], }); }); it("should check that each value should have label key", () => { expect( selectColumnOptionsValidation( [[{ value: "1" }, { value: "2" }]], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [[{ value: "1" }, { value: "2" }]], messages: [ `Invalid entry at Row: 0 index: 0. Missing required key: label`, ], }); expect( selectColumnOptionsValidation( [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [{ value: "1" }, { value: "2" }], ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [{ value: "1" }, { value: "2" }], ], messages: [ `Invalid entry at Row: 1 index: 0. Missing required key: label`, ], }); }); it("should check that each value should have value key", () => { expect( selectColumnOptionsValidation( [[{ label: "1" }, { label: "2" }]], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [[{ label: "1" }, { label: "2" }]], messages: [ `Invalid entry at Row: 0 index: 0. Missing required key: value`, ], }); expect( selectColumnOptionsValidation( [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [{ label: "1" }, { label: "2" }], ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [{ label: "1" }, { label: "2" }], ], messages: [ `Invalid entry at Row: 1 index: 0. Missing required key: value`, ], }); }); it("should check that each value should have unique value", () => { expect( selectColumnOptionsValidation( [ [ { label: "1", value: "1" }, { label: "2", value: "1" }, ], ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: false, parsed: [ [ { label: "1", value: "1" }, { label: "2", value: "1" }, ], ], messages: [ "Duplicate values found for the following properties, in the array entries, that must be unique -- value.", ], }); expect( selectColumnOptionsValidation( [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], ], messages: [""], }); }); it("should check that array of arrays of label, value is valid", () => { expect( selectColumnOptionsValidation( [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], ], messages: [""], }); }); it("should check that array of JSON is valid", () => { expect( selectColumnOptionsValidation( [ JSON.stringify([ { label: "1", value: "1" }, { label: "2", value: "2" }, ]), JSON.stringify([ { label: "1", value: "1" }, { label: "2", value: "2" }, ]), ], {} as TableWidgetProps, _, ), ).toEqual({ isValid: true, parsed: [ [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], [ { label: "1", value: "1" }, { label: "2", value: "2" }, ], ], messages: [""], }); }); }); }); describe("updateCustomColumnAliasOnLabelChange", () => { it("should return the propertyToUpdate array to update alias for the given custom column", () => { expect( updateCustomColumnAliasOnLabelChange( {} as TableWidgetProps, "primaryColumns.customColumn1.label", "customColumn12", ), ).toEqual([ { propertyPath: "primaryColumns.customColumn1.alias", propertyValue: "customColumn12", }, ]); }); it("should not return propertyToUpdate array to update alias for the given column", () => { expect( updateCustomColumnAliasOnLabelChange( {} as TableWidgetProps, "primaryColumns.resume_url.label", "customColumn12", ), ).toEqual(undefined); }); it("should not return the propertyToUpdate array to update alias when any property other than label property of the custom column gets changed", () => { expect( updateCustomColumnAliasOnLabelChange( {} as TableWidgetProps, "primaryColumns.customColumn1.notlabel", "customColumn12", ), ).toEqual(undefined); }); it("should return the propertyToUpdate array to update alias for any given custom column", () => { expect( updateCustomColumnAliasOnLabelChange( {} as TableWidgetProps, "primaryColumns.customColumn12345.label", "customColumn12", ), ).toEqual([ { propertyPath: "primaryColumns.customColumn12345.alias", propertyValue: "customColumn12", }, ]); }); }); describe("allowedFirstDayOfWeekRange", () => { it("should return valid object value is within 0 to 6", () => { expect(allowedFirstDayOfWeekRange(4)).toEqual({ isValid: true, parsed: 4, messages: [], }); }); it("should return valid object value is within 0 to 6", () => { expect(allowedFirstDayOfWeekRange(0)).toEqual({ isValid: true, parsed: 0, messages: [], }); }); it("should return invalid object when value is not within 0 to 6", () => { expect(allowedFirstDayOfWeekRange(8)).toEqual({ isValid: false, parsed: 0, messages: ["Number should be between 0-6."], }); }); it("should return invalid object when value is not within 0 to 6", () => { expect(allowedFirstDayOfWeekRange(-2)).toEqual({ isValid: false, parsed: 0, messages: ["Number should be between 0-6."], }); }); });
2,085
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TableWidgetV2/widget/utilities.test.ts
import type { ColumnProperties, TableStyles } from "../component/Constants"; import { StickyType } from "../component/Constants"; import { ColumnTypes } from "../constants"; import { convertNumToCompactString, escapeString, generateNewColumnOrderFromStickyValue, getAllTableColumnKeys, getArrayPropertyValue, getColumnType, getDerivedColumns, getHeaderClassNameOnDragDirection, getOriginalRowIndex, getSelectOptions, getSelectRowIndex, getSelectRowIndices, getSourceDataAndCaluclateKeysForEventAutoComplete, getTableStyles, reorderColumns, } from "./utilities"; const getCurrentRowBinding = ( entityName: string, userInput: string, withBinding = true, ) => { let rowBinding = `${entityName}.processedTableData.map((currentRow, currentIndex) => ( ${userInput}))`; if (withBinding) rowBinding = `{{${rowBinding}}}`; return rowBinding; }; describe("getOriginalRowIndex", () => { it("With no new data ", () => { const oldTableData = [ { step: "#1", task: " a fetch_users wih the Mock DB", status: "--", }, { step: "#2", task: " a fetch_users wih the Mock DB", status: "--", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", }, ]; const newTableData: Record<string, unknown>[] = []; const selectedRowIndex = 1; const result = getOriginalRowIndex( oldTableData, newTableData, selectedRowIndex, "step", ); const expected = -1; expect(result).toStrictEqual(expected); }); it("With no old data", () => { const oldTableData: Record<string, unknown>[] = []; const newTableData = [ { step: "#1", task: " a fetch_users wih the Mock DB", status: "--", }, { step: "#2", task: " a fetch_users wih the Mock DB", status: "--", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", }, ]; const selectedRowIndex = 1; const result = getOriginalRowIndex( oldTableData, newTableData, selectedRowIndex, "step", ); const expected = 1; expect(result).toStrictEqual(expected); }); it("With no selectedRowIndex", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const result = getOriginalRowIndex( oldTableData, newTableData, undefined, "step", ); const expected = -1; expect(result).toStrictEqual(expected); }); it("With no data", () => { const oldTableData = undefined; const newTableData = undefined; const selectedRowIndex = 1; const result = getOriginalRowIndex( oldTableData as any as Array<Record<string, unknown>>, newTableData as any as Array<Record<string, unknown>>, selectedRowIndex, "step", ); const expected = -1; expect(result).toStrictEqual(expected); }); it("With selectedRowIndex and data", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 0, __primaryKey__: "#3", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 2, __primaryKey__: "#1", }, ]; const result = getOriginalRowIndex(oldTableData, newTableData, 0, "step"); const expected = 2; expect(result).toStrictEqual(expected); }); it("With invalid primaryColumnId", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 0, __primaryKey__: "#3", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 2, __primaryKey__: "#1", }, ]; const result = getOriginalRowIndex(oldTableData, newTableData, 0, ""); const expected = -1; expect(result).toStrictEqual(expected); }); it("With new primaryColumn values", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 0, __primaryKey__: "#31", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#21", }, { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 2, __primaryKey__: "#11", }, ]; const result = getOriginalRowIndex(oldTableData, newTableData, 0, ""); const expected = -1; expect(result).toStrictEqual(expected); }); }); describe("selectRowIndex", () => { it("With new Data", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const selectedRowIndexProp = 0; const defaultSelectedRowIndex = 0; const result = getSelectRowIndex( oldTableData, newTableData, defaultSelectedRowIndex, selectedRowIndexProp, "step", ); expect(result).toStrictEqual(0); }); it("With new Data and different order", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 0, __primaryKey__: "#3", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 2, __primaryKey__: "#1", }, ]; const selectedRowIndexProp = 0; const defaultSelectedRowIndex = 0; const result = getSelectRowIndex( oldTableData, newTableData, defaultSelectedRowIndex, selectedRowIndexProp, "step", ); expect(result).toStrictEqual(2); }); it("With new Data and no primaryColumnId", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 0, __primaryKey__: "#3", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 2, __primaryKey__: "#1", }, ]; const selectedRowIndexProp = -1; const defaultSelectedRowIndex = 0; const result = getSelectRowIndex( oldTableData, newTableData, defaultSelectedRowIndex, selectedRowIndexProp, undefined, ); expect(result).toStrictEqual(0); }); it("With new Data and primaryColumnId, without selectRowIndex", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 0, __primaryKey__: "#3", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 2, __primaryKey__: "#1", }, ]; const selectedRowIndexProp = -1; const defaultSelectedRowIndex = 0; const result = getSelectRowIndex( oldTableData, newTableData, defaultSelectedRowIndex, selectedRowIndexProp, "step", ); expect(result).toStrictEqual(0); }); it("With new Data and primaryColumnId, without selectRowIndex, defaultRowIndex", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 0, __primaryKey__: "#3", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 2, __primaryKey__: "#1", }, ]; const selectedRowIndexProp = -1; const defaultSelectedRowIndex = -1; const result = getSelectRowIndex( oldTableData, newTableData, defaultSelectedRowIndex, selectedRowIndexProp, "step", ); expect(result).toStrictEqual(-1); }); }); describe("selectRowIndices", () => { it("With no selected index", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const defaultSelectedRowIndices = [0]; const result = getSelectRowIndices( oldTableData, newTableData, defaultSelectedRowIndices, [], undefined, ); expect(result).toEqual([0]); }); it("With selected indices and defaultRowIndices", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "2", }, ]; const defaultSelectedRowIndices = undefined; const result = getSelectRowIndices( oldTableData, newTableData, defaultSelectedRowIndices, [], undefined, ); expect(result).toEqual([]); }); it("With selected indices and no primaryColumnid", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const defaultSelectedRowIndices = undefined; const result = getSelectRowIndices( oldTableData, newTableData, defaultSelectedRowIndices, [0], undefined, ); expect(result).toEqual([]); }); it("With selected indices and primaryColumnid", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const defaultSelectedRowIndices = undefined; const result = getSelectRowIndices( oldTableData, newTableData, defaultSelectedRowIndices, [0], "step", ); expect(result).toEqual([0]); }); it("With selected indices, primaryColumnid and new order", () => { const oldTableData = [ { step: "#1", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 0, __primaryKey__: "#1", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 2, __primaryKey__: "#3", }, ]; const newTableData = [ { step: "#3", task: "Bind the query => fetch_users.data", status: "--", __originalIndex__: 0, __primaryKey__: "#3", }, { step: "#2", task: "fetch_users with the Mock DB", status: "--", __originalIndex__: 1, __primaryKey__: "#2", }, { step: "#1", task: " a fetch_users with the Mock DB", status: "--", __originalIndex__: 2, __primaryKey__: "#1", }, ]; const defaultSelectedRowIndices = undefined; const result = getSelectRowIndices( oldTableData, newTableData, defaultSelectedRowIndices, [0, 2], "step", ); expect(result).toEqual([2, 0]); }); }); describe("getAllTableColumnKeys - ", () => { it("should test with a valid tableData", () => { const tableData = [ { name: "jest", type: "unit", }, { name: "cypress", type: "integration", }, ]; expect(getAllTableColumnKeys(tableData)).toEqual(["name", "type"]); }); it("should test with a valid tableData with varying schema", () => { const tableData = [ { name: "jest", type: "unit", typescript: true, }, { name: "cypress", type: "integration", coverage: "56%", }, ]; expect(getAllTableColumnKeys(tableData)).toEqual([ "name", "type", "typescript", "coverage", ]); }); it("should test with a empty tableData", () => { expect(getAllTableColumnKeys([] as Array<Record<string, unknown>>)).toEqual( [], ); }); it("should test with undefined", () => { expect( getAllTableColumnKeys(undefined as any as Array<Record<string, unknown>>), ).toEqual([]); }); }); describe("getTableStyles - ", () => { it("should test with valid values", () => { expect( getTableStyles({ textColor: "#fff", textSize: "HEADING1", fontStyle: "12", cellBackground: "#f00", verticalAlignment: "TOP", horizontalAlignment: "CENTER", }) as any as TableStyles, ).toEqual({ textColor: "#fff", textSize: "HEADING1", fontStyle: "12", cellBackground: "#f00", verticalAlignment: "TOP", horizontalAlignment: "CENTER", }); }); }); describe("getDerivedColumns - ", () => { it("should check with primary columns without derived columns", () => { const primaryColumns = { column1: { isDerived: false, id: "column1", }, column2: { isDerived: false, id: "column2", }, column3: { isDerived: false, id: "column3", }, }; expect( getDerivedColumns( primaryColumns as any as Record<string, ColumnProperties>, ), ).toEqual({}); }); it("should check with primary columns with derived columns", () => { const primaryColumns = { column1: { isDerived: true, id: "column1", }, column2: { isDerived: false, id: "column2", }, column3: { isDerived: false, id: "column3", }, }; expect( getDerivedColumns( primaryColumns as any as Record<string, ColumnProperties>, ), ).toEqual({ column1: { isDerived: true, id: "column1", }, }); }); it("should check with primary columns with all derived columns", () => { const primaryColumns = { column1: { isDerived: true, id: "column1", }, column2: { isDerived: true, id: "column2", }, column3: { isDerived: true, id: "column3", }, }; expect( getDerivedColumns( primaryColumns as any as Record<string, ColumnProperties>, ), ).toEqual({ column1: { isDerived: true, id: "column1", }, column2: { isDerived: true, id: "column2", }, column3: { isDerived: true, id: "column3", }, }); }); it("should check with undefined", () => { expect( getDerivedColumns(undefined as any as Record<string, ColumnProperties>), ).toEqual({}); }); it("should check with simple string", () => { expect( getDerivedColumns("test" as any as Record<string, ColumnProperties>), ).toEqual({}); }); it("should check with number", () => { expect( getDerivedColumns(1 as any as Record<string, ColumnProperties>), ).toEqual({}); }); }); describe("escapeString", () => { it("should test that string without quotes are retured as it is", () => { ["column", "1", "columnNameThatIsReallyLong"].forEach((str) => { expect(escapeString(str)).toBe(str); }); }); it("should test that string with quotes are escaped correctly", () => { [ { input: `column"`, output: `column\"`, }, { input: `1"`, output: `1\"`, }, { input: `columnName " ThatIsReallyLong`, output: `columnName \" ThatIsReallyLong`, }, ].forEach(({ input, output }) => { expect(escapeString(input)).toBe(output); }); }); it("should test that string with escaped quotes are returned as it is", () => { [ `column\"`, `column\\\"`, `column\\\\\"`, `col\\\\\"umn\\\\\"`, `1\"`, `columnNameThatIsReallyLong\"`, ].forEach((str) => { expect(escapeString(str)).toBe(str); }); }); }); const MOCK_COLUMNS: Record<string, any> = { id: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.id"), textSize: "PARAGRAPH", index: 0, isVisible: true, label: "id", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "id", verticalAlignment: "CENTER", isEditable: false, isCellEditable: false, allowCellWrapping: false, }, name: { index: 1, width: 150, id: "name", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "name", computedValue: getCurrentRowBinding("Table1", "currentRow.name"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, createdAt: { index: 2, width: 150, id: "createdAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "createdAt", computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, updatedAt: { index: 3, width: 150, id: "updatedAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "updatedAt", computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, status: { index: 4, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "status", computedValue: getCurrentRowBinding("Table1", "currentRow.status"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, gender: { index: 5, width: 150, id: "gender", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "gender", computedValue: getCurrentRowBinding("Table1", "currentRow.gender"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, avatar: { index: 6, width: 150, id: "avatar", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "avatar", computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, address: { index: 8, width: 150, id: "address", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, role: { index: 9, id: "role", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, width: 150, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, dob: { index: 10, width: 150, id: "dob", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "dob", computedValue: getCurrentRowBinding("Table1", "currentRow.dob"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, phoneNo: { index: 11, width: 150, id: "phoneNo", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "phoneNo", computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, email: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.email"), textSize: "PARAGRAPH", index: 1, isVisible: true, label: "email", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "email", verticalAlignment: "CENTER", isEditable: false, isCellEditable: false, allowCellWrapping: false, }, }; describe("reorderColumns", () => { it("correctly reorders columns", () => { const columnOrder = [ "phoneNo", "id", "name", "createdAt", "updatedAt", "status", "gender", "avatar", "email", "address", "role", "dob", ]; const expected = { phoneNo: { index: 0, width: 150, id: "phoneNo", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "phoneNo", computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, id: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.id"), textSize: "PARAGRAPH", index: 1, isVisible: true, label: "id", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "id", verticalAlignment: "CENTER", isEditable: false, isCellEditable: false, allowCellWrapping: false, }, name: { index: 2, width: 150, id: "name", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "name", computedValue: getCurrentRowBinding("Table1", "currentRow.name"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, createdAt: { index: 3, width: 150, id: "createdAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "createdAt", computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, updatedAt: { index: 4, width: 150, id: "updatedAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "updatedAt", computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, status: { index: 5, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "status", computedValue: getCurrentRowBinding("Table1", "currentRow.status"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, gender: { index: 6, width: 150, id: "gender", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "gender", computedValue: getCurrentRowBinding("Table1", "currentRow.gender"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, avatar: { index: 7, width: 150, id: "avatar", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "avatar", computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, email: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.email"), textSize: "PARAGRAPH", index: 8, isVisible: true, label: "email", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "email", verticalAlignment: "CENTER", isEditable: false, isCellEditable: false, allowCellWrapping: false, }, address: { index: 9, width: 150, id: "address", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, role: { index: 10, id: "role", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, width: 150, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, dob: { index: 11, width: 150, id: "dob", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "dob", computedValue: getCurrentRowBinding("Table1", "currentRow.dob"), isEditable: false, isCellEditable: false, allowCellWrapping: false, }, }; const result = reorderColumns(MOCK_COLUMNS, columnOrder); expect(expected).toEqual(result); }); it("Ignores duplicates in column order and includes all columns", () => { const columnOrder = [ "phoneNo", "id", "name", "createdAt", "updatedAt", "status", "status", "gender", "avatar", "email", ]; const expected = { phoneNo: { index: 0, width: 150, id: "phoneNo", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "phoneNo", computedValue: getCurrentRowBinding("Table1", "currentRow.phoneNo"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, id: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.id"), textSize: "PARAGRAPH", index: 1, isVisible: true, label: "id", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "id", verticalAlignment: "CENTER", allowCellWrapping: false, isCellEditable: false, isEditable: false, }, name: { index: 2, width: 150, id: "name", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "name", computedValue: getCurrentRowBinding("Table1", "currentRow.name"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, createdAt: { index: 3, width: 150, id: "createdAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "createdAt", computedValue: getCurrentRowBinding("Table1", "currentRow.createdAt"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, updatedAt: { index: 4, width: 150, id: "updatedAt", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "updatedAt", computedValue: getCurrentRowBinding("Table1", "currentRow.updatedAt"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, status: { index: 5, width: 150, id: "status", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "status", computedValue: getCurrentRowBinding("Table1", "currentRow.status"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, gender: { index: 6, width: 150, id: "gender", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "gender", computedValue: getCurrentRowBinding("Table1", "currentRow.gender"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, avatar: { index: 7, width: 150, id: "avatar", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "avatar", computedValue: getCurrentRowBinding("Table1", "currentRow.avatar"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, email: { isDerived: false, computedValue: getCurrentRowBinding("Table1", "currentRow.email"), textSize: "PARAGRAPH", index: 8, isVisible: true, label: "email", columnType: "text", horizontalAlignment: "LEFT", width: 150, enableFilter: true, enableSort: true, id: "email", verticalAlignment: "CENTER", allowCellWrapping: false, isCellEditable: false, isEditable: false, }, address: { index: 9, width: 150, id: "address", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, role: { index: 10, id: "role", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, width: 150, label: "address", computedValue: getCurrentRowBinding("Table1", "currentRow.address"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, dob: { index: 11, width: 150, id: "dob", horizontalAlignment: "LEFT", verticalAlignment: "CENTER", columnType: "text", textSize: "PARAGRAPH", enableFilter: true, enableSort: true, isVisible: true, isDerived: false, label: "dob", computedValue: getCurrentRowBinding("Table1", "currentRow.dob"), allowCellWrapping: false, isCellEditable: false, isEditable: false, }, }; const result = reorderColumns(MOCK_COLUMNS, columnOrder); expect(expected).toEqual(result); }); }); describe("getColumnType", () => { const tableData = [ { id: 1, gender: "female", latitude: -45.7997, longitude: null, dob: null, phone: null, email: "[email protected]", image: "https://randomuser.me/api/portraits/med/women/39.jpg", country: "Germany", name: "Bene", checked: true, }, { id: 2, gender: "male", latitude: "42.9756", longitude: null, dob: null, phone: null, email: "[email protected]", image: "https://randomuser.me/api/portraits/med/women/6.jpg", country: "Netherlandss", name: "AliceBggg11144", checked: false, }, { id: 3, gender: "female", latitude: "-14.0884", longitude: 27.0428, dob: null, phone: null, email: null, image: "https://randomuser.me/api/portraits/med/women/88.jpg", country: "Norway", name: null, checked: true, }, { id: 4, gender: "male", latitude: "-88.0169", longitude: "-118.7708", dob: "1984-02-25T07:31:12.723Z", phone: "594-620-3202", email: "[email protected]", image: "https://randomuser.me/api/portraits/med/men/52.jpg", country: "Cornwall", name: "Jack1", }, { id: 5, gender: "female", latitude: "73.6320", longitude: "-167.3976", dob: null, phone: null, email: "", image: "https://randomuser.me/api/portraits/med/women/91.jpg", country: "United Kingdom", name: "Sue", premium: false, }, { id: 6, gender: "male", latitude: "86.1891", longitude: "-56.8442", dob: "1959-02-20T02:42:20.579Z", phone: "61521059", email: "[email protected]", image: "https://randomuser.me/api/portraits/med/men/58.jpg", country: "Norway", name: "Allih Persson", }, { id: 7, gender: "male", latitude: "-83.6654", longitude: "87.6481", dob: "1952-02-22T18:47:29.476Z", phone: "(212)-051-1147", email: "[email protected]", image: "https://randomuser.me/api/portraits/med/women/30.jpg", country: "United States", name: "Julia Armstrong", }, { id: 8, gender: "female", latitude: "38.7394", longitude: "-31.7919", dob: "1955-10-07T11:31:49.823Z", phone: "(817)-164-4040", email: "[email protected]", image: "https://randomuser.me/api/portraits/med/women/88.jpg", country: "Netherlands", name: "Shiva Duijf", }, { id: 9, gender: "male", latitude: "4.5623", longitude: "9.0901", dob: null, phone: null, email: null, image: "https://randomuser.me/api/portraits/med/men/30.jpg", country: "Norway", name: null, }, { id: 10, gender: "male", latitude: "-49.4156", longitude: "-132.3755", dob: "1977-03-27T02:12:01.151Z", phone: "212-355-8035", email: "[email protected]", image: "https://randomuser.me/api/portraits/med/men/73.jpg", country: "Canada", name: "David Mackay", }, ]; it("returns NUMBER column type for number value", () => { const result = getColumnType(tableData, "id"); expect(ColumnTypes.NUMBER).toEqual(result); }); it("returns TEXT column type for empty columnKey", () => { const result = getColumnType(tableData, ""); expect(ColumnTypes.TEXT).toEqual(result); }); it("returns TEXT column type for string value", () => { const result = getColumnType(tableData, "gender"); expect(ColumnTypes.TEXT).toEqual(result); }); it("returns TEXT column type for string columnKey that does not exist in tableData", () => { const result = getColumnType(tableData, "coordinates"); expect(ColumnTypes.TEXT).toEqual(result); }); it("returns CHECKBOX column type for columnKey that has boolean columnValue", () => { const result = getColumnType(tableData, "checked"); expect(ColumnTypes.CHECKBOX).toEqual(result); }); it("returns proper column type for columnKey that has first few rows data as null", () => { const result = getColumnType(tableData, "longitude"); expect(ColumnTypes.NUMBER).toEqual(result); }); it("returns proper column type for columnKey that does not exist in the first few rows", () => { const result = getColumnType(tableData, "premium"); expect(ColumnTypes.CHECKBOX).toEqual(result); }); it("returns Date column type for valid Date field", () => { const result = getColumnType(tableData, "dob"); expect(ColumnTypes.DATE).toEqual(result); }); }); describe("getSourceDataAndCaluclateKeysForEventAutoComplete", () => { it("Should test with valid values", () => { const mockProps = { type: "TABLE_WIDGET_V2", widgetName: "Table1", widgetId: "9oh3qyw84m", primaryColumns: { action: { configureMenuItems: { config: { label: "{{Table1.primaryColumns.action.sourceData.map((currentItem, currentIndex) => ( currentItem.))}}", }, }, }, }, __evaluation__: { errors: { primaryColumns: [], }, evaluatedValues: { primaryColumns: { step: { index: 0, width: 150, id: "step", originalId: "step", alias: "step", columnType: "text", label: "step", computedValue: ["#1", "#2", "#3"], validation: {}, labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", originalId: "action", alias: "action", columnType: "menuButton", label: "action", computedValue: ["", "", ""], labelColor: "#FFFFFF", buttonLabel: ["Action", "Action", "Action"], menuColor: ["#553DE9", "#553DE9", "#553DE9"], menuItemsSource: "DYNAMIC", menuButtonLabel: ["Open Menu", "Open Menu", "Open Menu"], sourceData: [ { gender: "male", name: "Victor", email: "[email protected]", }, { gender: "male", name: "Tobias", email: "[email protected]", }, { gender: "female", name: "Jane", email: "[email protected]", }, { gender: "female", name: "Yaromira", email: "[email protected]", }, { gender: "male", name: "Andre", email: "[email protected]", }, ], configureMenuItems: { label: "Configure menu items", id: "config", config: { id: "config", label: ["male", "male", "female", "female", "male"], isVisible: true, isDisabled: false, onClick: "", backgroundColor: ["red", "red", "tan", "tan", "red"], iconName: "add-row-top", iconAlign: "right", }, }, }, }, }, }, }; const result = getSourceDataAndCaluclateKeysForEventAutoComplete( mockProps as any, ); const expected = { currentItem: { name: "", email: "", gender: "", }, }; expect(result).toStrictEqual(expected); }); it("Should test with empty sourceData", () => { const mockProps = { type: "TABLE_WIDGET_V2", widgetName: "Table1", widgetId: "9oh3qyw84m", primaryColumns: { action: { configureMenuItems: { config: { label: "{{Table1.primaryColumns.action.sourceData.map((currentItem, currentIndex) => ( currentItem.))}}", }, }, }, }, __evaluation__: { errors: { primaryColumns: [], }, evaluatedValues: { primaryColumns: { step: { index: 0, width: 150, id: "step", originalId: "step", alias: "step", columnType: "text", label: "step", computedValue: ["#1", "#2", "#3"], validation: {}, labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", originalId: "action", alias: "action", columnType: "menuButton", label: "action", computedValue: ["", "", ""], labelColor: "#FFFFFF", buttonLabel: ["Action", "Action", "Action"], menuColor: ["#553DE9", "#553DE9", "#553DE9"], menuItemsSource: "DYNAMIC", menuButtonLabel: ["Open Menu", "Open Menu", "Open Menu"], sourceData: [], configureMenuItems: { label: "Configure menu items", id: "config", config: { id: "config", label: ["male", "male", "female", "female", "male"], isVisible: true, isDisabled: false, onClick: "", backgroundColor: ["red", "red", "tan", "tan", "red"], iconName: "add-row-top", iconAlign: "right", }, }, }, }, }, }, }; const result = getSourceDataAndCaluclateKeysForEventAutoComplete( mockProps as any, ); const expected = { currentItem: {} }; expect(result).toStrictEqual(expected); }); it("Should test without sourceData", () => { const mockProps = { type: "TABLE_WIDGET_V2", widgetName: "Table1", widgetId: "9oh3qyw84m", primaryColumns: { action: { configureMenuItems: { config: { label: "{{Table1.primaryColumns.action.sourceData.map((currentItem, currentIndex) => ( currentItem.))}}", }, }, }, }, __evaluation__: { errors: { primaryColumns: [], }, evaluatedValues: { primaryColumns: { step: { index: 0, width: 150, id: "step", originalId: "step", alias: "step", columnType: "text", label: "step", computedValue: ["#1", "#2", "#3"], validation: {}, labelColor: "#FFFFFF", }, action: { index: 3, width: 150, id: "action", originalId: "action", alias: "action", columnType: "menuButton", label: "action", computedValue: ["", "", ""], labelColor: "#FFFFFF", buttonLabel: ["Action", "Action", "Action"], menuColor: ["#553DE9", "#553DE9", "#553DE9"], menuItemsSource: "DYNAMIC", menuButtonLabel: ["Open Menu", "Open Menu", "Open Menu"], configureMenuItems: { label: "Configure menu items", id: "config", config: { id: "config", label: ["male", "male", "female", "female", "male"], isVisible: true, isDisabled: false, onClick: "", backgroundColor: ["red", "red", "tan", "tan", "red"], iconName: "add-row-top", iconAlign: "right", }, }, }, }, }, }, }; const result = getSourceDataAndCaluclateKeysForEventAutoComplete( mockProps as any, ); const expected = { currentItem: {} }; expect(result).toStrictEqual(expected); }); }); describe("getArrayPropertyValue", () => { it("should test that it returns the same value when value is not of expected type", () => { expect(getArrayPropertyValue("test", 1)).toEqual("test"); expect(getArrayPropertyValue(1, 1)).toEqual(1); }); it("should test that it returns the same value when value is empty", () => { expect(getArrayPropertyValue([], 1)).toEqual([]); }); it("should test that it returns the correct value when value is just array of label values", () => { expect( getArrayPropertyValue([{ label: "test", value: "test" }], 1), ).toEqual([{ label: "test", value: "test" }]); expect( getArrayPropertyValue( [ { label: "test", value: "test" }, { label: "test1", value: "test1" }, ], 1, ), ).toEqual([ { label: "test", value: "test" }, { label: "test1", value: "test1" }, ]); }); it("should test that it returns the correct value when value is an array of array of label values", () => { expect( getArrayPropertyValue( [ [ { label: "test1", value: "test1", }, ], [ { label: "test2", value: "test2", }, ], ], 1, ), ).toEqual([ { label: "test2", value: "test2", }, ]); expect( getArrayPropertyValue( [ [ { label: "test1", value: "test1", }, { label: "test2", value: "test2", }, ], [ { label: "test3", value: "test3", }, ], ], 0, ), ).toEqual([ { label: "test1", value: "test1", }, { label: "test2", value: "test2", }, ]); }); }); describe("generateNewColumnOrderFromStickyValue", () => { const baseTableConfig: { primaryColumns: Record<string, Pick<ColumnProperties, "sticky">>; columnOrder: string[]; columnName: string; sticky?: string; } = { primaryColumns: { step: { sticky: StickyType.NONE, }, task: { sticky: StickyType.NONE, }, status: { sticky: StickyType.NONE, }, action: { sticky: StickyType.NONE, }, }, columnOrder: ["step", "task", "status", "action"], columnName: "", sticky: "", }; let tableConfig: { primaryColumns: any; columnOrder: any; columnName?: string; sticky?: string | undefined; }; let newColumnOrder; const resetValues = (config: { primaryColumns: any; columnOrder: any; columnName?: string; sticky?: string | undefined; }) => { config.primaryColumns = { step: { sticky: "", id: "step", }, task: { sticky: "", id: "task", }, status: { sticky: "", id: "status", }, action: { sticky: "", id: "action", }, }; config.columnOrder = ["step", "task", "status", "action"]; config.columnName = ""; config.sticky = ""; return config; }; test("Column order should remain same when leftmost or the right-most columns are frozen", () => { tableConfig = { ...baseTableConfig }; newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, tableConfig.columnOrder, "step", "left", ); tableConfig.primaryColumns.step.sticky = "left"; expect(newColumnOrder).toEqual(["step", "task", "status", "action"]); newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, tableConfig.columnOrder, "action", "right", ); tableConfig.primaryColumns.action.sticky = "right"; expect(newColumnOrder).toEqual(["step", "task", "status", "action"]); }); test("Column that is frozen to left should appear first in the column order", () => { tableConfig = resetValues(baseTableConfig); newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, tableConfig.columnOrder, "action", "left", ); expect(newColumnOrder).toEqual(["action", "step", "task", "status"]); }); test("Column that is frozen to right should appear last in the column order", () => { tableConfig = resetValues(baseTableConfig); newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, tableConfig.columnOrder, "step", "right", ); expect(newColumnOrder).toEqual(["task", "status", "action", "step"]); }); test("Column that is frozen to left should appear after the last left frozen column in the column order", () => { tableConfig = resetValues(baseTableConfig); // Consisder step to be already frozen to left. tableConfig.primaryColumns.step.sticky = "left"; newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, tableConfig.columnOrder, "action", "left", ); expect(newColumnOrder).toEqual(["step", "action", "task", "status"]); }); test("Column that is frozen to right should appear before the first right frozen column in the column order", () => { tableConfig = resetValues(baseTableConfig); // Consisder action to be already frozen to right. tableConfig.primaryColumns.action.sticky = "right"; newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, tableConfig.columnOrder, "step", "right", ); expect(newColumnOrder).toEqual(["task", "status", "step", "action"]); }); test("When leftmost and rightmost columns are only frozen, then on unfreeze left column should be first and right most column should at last", () => { tableConfig = resetValues(baseTableConfig); // Consisder step to be left frozen and action to be frozen to right. tableConfig.primaryColumns.step.sticky = "left"; tableConfig.primaryColumns.action.sticky = "right"; newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, tableConfig.columnOrder, "step", "", ); tableConfig.primaryColumns.step.sticky = ""; expect(newColumnOrder).toEqual(["step", "task", "status", "action"]); newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, tableConfig.columnOrder, "action", "", ); expect(newColumnOrder).toEqual(["step", "task", "status", "action"]); }); test("Unfreezing first column from multiple left frozen columns, should place the unfrozen column after the last frozen column", () => { tableConfig = resetValues(baseTableConfig); // Consisder step to be left frozen and action to be frozen to right. tableConfig.primaryColumns.step.sticky = "left"; tableConfig.primaryColumns.action.sticky = "left"; tableConfig.primaryColumns.task.sticky = "left"; newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, ["step", "action", "task", "status"], "step", "", ); tableConfig.primaryColumns.step.sticky = ""; expect(newColumnOrder).toEqual(["action", "task", "step", "status"]); }); test("Unfreezing last column from multiple right frozen columns, should place the unfrozen column before the first frozen column", () => { tableConfig = resetValues(baseTableConfig); // Consisder step to be left frozen and action to be frozen to right. tableConfig.primaryColumns.step.sticky = "right"; tableConfig.primaryColumns.action.sticky = "right"; tableConfig.primaryColumns.task.sticky = "right"; newColumnOrder = generateNewColumnOrderFromStickyValue( tableConfig.primaryColumns as any, ["status", "step", "action", "task"], "task", "", ); tableConfig.primaryColumns.step.sticky = ""; expect(newColumnOrder).toEqual(["status", "task", "step", "action"]); }); }); describe("getHeaderClassNameOnDragDirection", () => { test("Should return left highlight class when dragging from right to left", () => { expect(getHeaderClassNameOnDragDirection(3, 2)).toEqual( "th header-reorder highlight-left", ); }); test("Should return right highlight class when dragging from left to right", () => { expect(getHeaderClassNameOnDragDirection(1, 2)).toEqual( "th header-reorder highlight-right", ); }); }); describe("getSelectOptions", () => { it("Should return select options when user is not adding a new row", () => { const columnProperties = { allowSameOptionsInNewRow: true, selectOptions: [ { label: "male", value: "male", }, { label: "female", value: "female", }, ], }; expect( getSelectOptions(false, 0, columnProperties as ColumnProperties), ).toEqual([ { label: "male", value: "male", }, { label: "female", value: "female", }, ]); // Check when select options are inside dynamic binding const columnPropertiesDynamicSelectOptions = { allowSameOptionsInNewRow: true, selectOptions: [ [ { label: "abc", value: "abc", }, ], [ { label: "efg", value: "efg", }, ], [ { label: "xyz", value: "xyz", }, ], ], }; expect( getSelectOptions( false, 0, columnPropertiesDynamicSelectOptions as ColumnProperties, ), ).toEqual([ { label: "abc", value: "abc", }, ]); }); it("Should return select options while adding a new row and when 'Same options in new row' option is turned on", () => { const columnProperties = { allowSameOptionsInNewRow: true, selectOptions: [ { label: "male", value: "male", }, { label: "female", value: "female", }, ], }; expect( getSelectOptions(true, -1, columnProperties as ColumnProperties), ).toEqual([ { label: "male", value: "male", }, { label: "female", value: "female", }, ]); }); it("Should return new row options", () => { const columnProperties = { allowSameOptionsInNewRow: false, newRowSelectOptions: [ { label: "abc", value: "abc", }, ], }; expect( getSelectOptions(true, -1, columnProperties as ColumnProperties), ).toEqual([ { label: "abc", value: "abc", }, ]); }); }); describe("convertNumToCompactString", () => { it("formats a number in thousands (K)", () => { expect(convertNumToCompactString(5000)).toBe("5.0K"); expect(convertNumToCompactString(9999)).toBe("10.0K"); // Rounding expect(convertNumToCompactString(123456)).toBe("123.5K"); // Rounding with precision }); it("formats a number in millions (M)", () => { expect(convertNumToCompactString(1500000)).toBe("1.5M"); expect(convertNumToCompactString(9999999)).toBe("10.0M"); // Rounding expect(convertNumToCompactString(123456789)).toBe("123.5M"); // Rounding with precision }); it("formats a number less than 1000 as is", () => { expect(convertNumToCompactString(42)).toBe("42"); expect(convertNumToCompactString(999)).toBe("999"); }); });
2,119
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TabsWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/TabsWidget/widget/index.test.tsx
import { buildChildren, widgetCanvasFactory, } from "test/factories/WidgetFactoryUtils"; import { render, fireEvent } from "test/testUtils"; import * as widgetRenderUtils from "utils/widgetRenderUtils"; import * as dataTreeSelectors from "selectors/dataTreeSelectors"; import * as editorSelectors from "selectors/editorSelectors"; import Canvas from "pages/Editor/Canvas"; import React from "react"; import { mockCreateCanvasWidget, mockGetWidgetEvalValues, MockPageDSL, } from "test/testCommon"; describe("Tabs widget functional cases", () => { jest .spyOn(dataTreeSelectors, "getWidgetEvalValues") .mockImplementation(mockGetWidgetEvalValues); jest .spyOn(editorSelectors, "computeMainContainerWidget") .mockImplementation((widget) => widget as any); jest .spyOn(widgetRenderUtils, "createCanvasWidget") .mockImplementation(mockCreateCanvasWidget); it("Should render 2 tabs by default", () => { const children: any = buildChildren([{ type: "TABS_WIDGET" }]); const dsl: any = widgetCanvasFactory.build({ children, }); const component = render( <MockPageDSL dsl={dsl}> <Canvas canvasWidth={dsl.rightColumn} pageId="page_id" widgetsStructure={dsl} /> </MockPageDSL>, ); const tab1 = component.queryByText("Tab 1"); const tab2 = component.queryByText("Tab 2"); expect(tab1).toBeDefined(); expect(tab2).toBeDefined(); }); it("Should render components inside tabs by default", () => { const tab1Children = buildChildren([ { type: "SWITCH_WIDGET", label: "Tab1 Switch" }, { type: "CHECKBOX_WIDGET", label: "Tab1 Checkbox" }, ]); const tab2Children = buildChildren([ { type: "INPUT_WIDGET_V2", text: "Tab2 Text" }, { type: "BUTTON_WIDGET", label: "Tab2 Button" }, ]); const children: any = buildChildren([{ type: "TABS_WIDGET" }]); children[0].children[0].children = tab1Children; children[0].children[1].children = tab2Children; const dsl: any = widgetCanvasFactory.build({ children, }); const component = render( <MockPageDSL dsl={dsl}> <Canvas canvasWidth={dsl.rightColumn} pageId="page_id" widgetsStructure={dsl} /> </MockPageDSL>, ); const tab1 = component.queryByText("Tab 1"); const tab2: any = component.queryByText("Tab 2"); expect(tab1).toBeDefined(); expect(tab2).toBeDefined(); let tab1Switch = component.queryByText("Tab1 Switch"); let tab1Checkbox = component.queryByText("Tab1 Checkbox"); let tab2Input = component.queryByText("Tab2 Text"); let tab2Button = component.queryByText("Tab2 Button"); expect(tab1Switch).toBeDefined(); expect(tab1Checkbox).toBeDefined(); expect(tab2Input).toBeNull(); expect(tab2Button).toBeNull(); fireEvent.click(tab2); tab1Switch = component.queryByText("Tab1 Switch"); tab1Checkbox = component.queryByText("Tab1 Checkbox"); tab2Input = component.queryByText("Tab2 Text"); tab2Button = component.queryByText("Tab2 Button"); expect(tab1Switch).toBeNull(); expect(tab1Checkbox).toBeNull(); expect(tab2Input).toBeDefined(); expect(tab2Button).toBeDefined(); }); });
2,204
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSCurrencyInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSCurrencyInputWidget/component/utilities.test.ts
import { getLocaleDecimalSeperator, getLocaleThousandSeparator, } from "widgets/WidgetUtils"; import { formatCurrencyNumber, limitDecimalValue, parseLocaleFormattedStringToNumber, } from "./utilities"; let locale = "en-US"; jest.mock("utils/helpers", () => { const originalModule = jest.requireActual("utils/helpers"); return { __esModule: true, ...originalModule, getLocale: () => { return locale; }, }; }); describe("Utilities - ", () => { it("should test formatCurrencyNumber", () => { //below values are in format of [no. of decimals, input, output] [ [0, "123", "123"], [1, "123", "123"], [2, "123", "123"], [0, "123.12", "123"], [1, "123.12", "123.1"], [2, "123.12", "123.12"], [2, "123456.12", "123,456.12"], [1, "123456.12", "123,456.1"], [0, "123456.12", "123,456"], [0, "12345678", "12,345,678"], [2, "12345678", "12,345,678"], [2, "0.22", "0.22"], [1, "0.22", "0.2"], [0, "0.22", "0"], [2, "0.22123123", "0.22"], [1, "0.22123123", "0.2"], [0, "0.22123123", "0"], [0, "4", "4"], [0, "4.9", "5"], [0, "4.2", "4"], [1, "4", "4"], [1, "4.9", "4.9"], [1, "4.99", "5.0"], [1, "4.10", "4.1"], [1, "4.12", "4.1"], [2, "4", "4"], [2, "4.90", "4.90"], [2, "4.9", "4.90"], [2, "4.99", "4.99"], [2, "4.10", "4.10"], [2, "4.1", "4.10"], [2, "4.11", "4.11"], [2, "4.119", "4.12"], [2, "4.111", "4.11"], [2, "4.999", "5.00"], ].forEach((d) => { expect(formatCurrencyNumber(d[0] as number, d[1] as string)).toBe(d[2]); }); }); it("should test limitDecimalValue", () => { [ [0, "123.12", "123"], [1, "123.12", "123.1"], [2, "123.12", "123.12"], [2, "123456.12", "123456.12"], [1, "123456.12", "123456.1"], [0, "123456.12", "123456"], [2, "0.22", "0.22"], [1, "0.22", "0.2"], [0, "0.22", "0"], [2, "0.22123123", "0.22"], [1, "0.22123123", "0.2"], [0, "0.22123123", "0"], ].forEach((d) => { expect(limitDecimalValue(d[0] as number, d[1] as string)).toBe(d[2]); }); }); it("should test getLocaleDecimalSeperator", () => { expect(getLocaleDecimalSeperator()).toBe("."); locale = "en-IN"; expect(getLocaleDecimalSeperator()).toBe("."); locale = "hr-HR"; expect(getLocaleDecimalSeperator()).toBe(","); }); it("should test getLocaleThousandSeparator", () => { locale = "en-US"; expect(getLocaleThousandSeparator()).toBe(","); locale = "en-IN"; expect(getLocaleThousandSeparator()).toBe(","); locale = "hr-HR"; expect(getLocaleThousandSeparator()).toBe("."); }); it("shoud test parseLocaleFormattedStringToNumber", () => { locale = "en-US"; [ ["123", 123], ["123.12", 123.12], ["123,456.12", 123456.12], ["123,456,789.12", 123456789.12], ["0.22", 0.22], ["0.22123123", 0.22123123], ].forEach((d) => { expect(parseLocaleFormattedStringToNumber(d[0] as string)).toBe(d[1]); }); locale = "hr-HR"; [ ["123", 123], ["123,12", 123.12], ["123.456,12", 123456.12], ["123.456.789,12", 123456789.12], ["0,22", 0.22], ["0,22123123", 0.22123123], ].forEach((d) => { expect(parseLocaleFormattedStringToNumber(d[0] as string)).toBe(d[1]); }); }); });
2,207
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSCurrencyInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSCurrencyInputWidget/widget/derived.test.ts
import derivedProperty from "./derived"; describe("Derived property - ", () => { describe("isValid property", () => { it("should test isRequired", () => { let isValid = derivedProperty.isValid({ text: undefined, isRequired: false, }); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid({ text: undefined, isRequired: true, }); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid({ value: 100, text: "100", isRequired: true, }); expect(isValid).toBeTruthy(); }); it("should test validation", () => { let isValid = derivedProperty.isValid({ value: 100, text: "100", validation: false, }); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid({ value: 100, text: "100", validation: true, }); expect(isValid).toBeTruthy(); }); it("should test regex validation", () => { let isValid = derivedProperty.isValid({ value: 100, text: "100", regex: "^100$", }); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid({ value: 101, text: "101", regex: "^100$", }); expect(isValid).toBeFalsy(); }); }); });
2,208
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSCurrencyInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSCurrencyInputWidget/widget/helpers.test.ts
import { countryToFlag } from "./helpers"; describe("countryToFlag", () => { it("should test countryToFlag", () => { [ ["IN", "🇮🇳"], ["in", "🇮🇳"], ["US", "🇺🇸"], ].forEach((d) => { expect(countryToFlag(d[0])).toBe(d[1]); }); String.fromCodePoint = undefined as any; [ ["IN", "IN"], ["in", "in"], ["US", "US"], ].forEach((d) => { expect(countryToFlag(d[0])).toBe(d[1]); }); }); });
2,210
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSCurrencyInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSCurrencyInputWidget/widget/index.test.tsx
import type { CurrencyInputWidgetProps } from "./types"; import { defaultValueValidation } from "./config/propertyPaneConfig/validations"; import _ from "lodash"; describe("defaultValueValidation", () => { let result: any; it("should validate defaulttext", () => { result = defaultValueValidation("100", {} as CurrencyInputWidgetProps, _); expect(result).toEqual({ isValid: true, parsed: "100", messages: [{ name: "", message: "" }], }); result = defaultValueValidation("test", {} as CurrencyInputWidgetProps, _); expect(result).toEqual({ isValid: false, parsed: undefined, messages: [ { name: "TypeError", message: "This value must be number", }, ], }); result = defaultValueValidation("", {} as CurrencyInputWidgetProps, _); expect(result).toEqual({ isValid: true, parsed: undefined, messages: [{ name: "", message: "" }], }); }); it("should validate defaulttext with object value", () => { const value = {}; result = defaultValueValidation(value, {} as CurrencyInputWidgetProps, _); expect(result).toEqual({ isValid: false, parsed: JSON.stringify(value, null, 2), messages: [ { name: "TypeError", message: "This value must be number", }, ], }); }); });
2,245
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSInputWidget/widget/derived.test.ts
import _ from "lodash"; import { InputTypes } from "widgets/BaseInputWidget/constants"; import derivedProperty from "./derived"; describe("Derived property - ", () => { describe("isValid property", () => { it("should test isRequired", () => { //Number input with required false and empty value let isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: undefined, isRequired: false, }, null, _, ); expect(isValid).toBeTruthy(); //Number input with required true and invalid value isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: "test", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Number input with required true and invalid value `null` isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: null, isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Number input with required true and invalid value `undefined` isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: undefined, isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Number input with required true and invalid value `""` isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Number input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: 1, isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); //Number input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: 1.1, isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); //Text input with required false and empty value isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, rawText: "", isRequired: false, }, null, _, ); expect(isValid).toBeTruthy(); //Text input with required true and invalid value isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, rawText: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Text input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, rawText: "test", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); //Email input with required false and empty value isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "", isRequired: false, }, null, _, ); expect(isValid).toBeTruthy(); //Email input with required true and invalid value isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Email input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "[email protected]", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); //Password input with required false and empty value isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, rawText: "", isRequired: false, }, null, _, ); expect(isValid).toBeTruthy(); //Password input with required true and invalid value isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, rawText: "", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); //Password input with required true and valid value isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, rawText: "admin", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("should test validation", () => { let isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, rawText: "test", isRequired: true, validation: false, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, rawText: "test", isRequired: true, validation: true, }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: 1, isRequired: true, validation: false, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: 1, isRequired: true, validation: true, }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "[email protected]", isRequired: true, validation: false, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "[email protected]", isRequired: true, validation: true, }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, rawText: "admin123", isRequired: true, validation: false, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, rawText: "admin123", isRequired: true, validation: true, }, null, _, ); expect(isValid).toBeTruthy(); }); it("should test regex validation", () => { let isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, rawText: "test", isRequired: true, regex: "^test$", }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.TEXT, rawText: "test123", isRequired: true, regex: "^test$", }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: 1, isRequired: true, regex: "^1$", }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.NUMBER, rawText: 2, isRequired: true, regex: "^1$", }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "[email protected]", isRequired: true, regex: "^[email protected]$", }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "[email protected]", isRequired: true, regex: "^[email protected]$", }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, rawText: "admin123", isRequired: true, regex: "^admin123$", }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.PASSWORD, rawText: "admin1234", isRequired: true, regex: "^admin123$", }, null, _, ); expect(isValid).toBeFalsy(); }); it("should test email type built in validation", () => { let isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "[email protected]", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "test", isRequired: true, }, null, _, ); expect(isValid).toBeFalsy(); isValid = derivedProperty.isValid( { inputType: InputTypes.EMAIL, rawText: "[email protected]", isRequired: true, }, null, _, ); expect(isValid).toBeTruthy(); }); }); });
2,246
0
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSInputWidget
petrpan-code/appsmithorg/appsmith/app/client/src/widgets/wds/WDSInputWidget/widget/helper.test.ts
import { InputTypes } from "widgets/BaseInputWidget/constants"; import { parseText } from "./helper"; describe("getParsedText", () => { it("should test with all possible values", () => { let text; text = parseText("test", InputTypes.TEXT); expect(text).toBe("test"); text = parseText("test1", InputTypes.PASSWORD); expect(text).toBe("test1"); text = parseText("[email protected]", InputTypes.EMAIL); expect(text).toBe("[email protected]"); text = parseText("", InputTypes.NUMBER); expect(text).toBe(null); text = parseText(undefined as unknown as string, InputTypes.NUMBER); expect(text).toBe(null); text = parseText(null as unknown as string, InputTypes.NUMBER); expect(text).toBe(null); text = parseText(1 as unknown as string, InputTypes.NUMBER); expect(text).toBe(1); text = parseText("1.01", InputTypes.NUMBER); expect(text).toBe(1.01); text = parseText("1.00", InputTypes.NUMBER); expect(text).toBe(1); }); });